我已经建立了一个从底部出现并在一段时间后隐藏的 View ,并且效果很好,但是我想在UIView类中将其作为模态,我在互联网上看了一下,但我无法理解该怎么做。

snake = UIView(frame: CGRect(x: 0 , y: self.view.frame.size.height-66, width: self.view.frame.size.width, height: 66))
snake.backgroundColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0)


let label = UILabel(frame: CGRect(x: 12, y: 8, width: snake.frame.size.width-90, height: 50))
label.text = "Connection error please try again later!!"
label.textColor = UIColor.whiteColor()
label.numberOfLines = 0
label.font = UIFont.systemFontOfSize(14)
snake.addSubview(label)

let button = UIButton(frame: CGRect(x: snake.frame.size.width-87, y: 8, width: 86, height: 50))
button.setTitle("OK", forState: UIControlState.Normal)
button.setTitleColor(UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1.0), forState: UIControlState.Normal)
button.addTarget(self, action: "hideSnackBar:", forControlEvents: UIControlEvents.TouchUpInside)
snake.addSubview(button)
self.view.addSubview(snake)

如何从此类开始,我不知道,我正在以编程方式及其框架创建 View ,并且需要为按钮或标签设置属性,并从任何类创建 View 。
class snake: UIView {


    override init (frame : CGRect) {
        super.init(frame : frame)

    }

    convenience init () {
        self.init(frame:CGRect.zero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }

}

最佳答案

代码:

 var label:UILabel!
var button:UIButton!

override init (frame : CGRect) {
    super.init(frame : frame)
    self.backgroundColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0)


    label = UILabel(frame: CGRect(x: 12, y: 8, width: self.frame.size.width-90, height: 50))
    label.text = "Connection error please try again later!!"
    label.textColor = UIColor.whiteColor()
    label.numberOfLines = 0
    label.font = UIFont.systemFontOfSize(14)
    self.addSubview(label)

    button = UIButton(frame: CGRect(x: self.frame.size.width-87, y: 8, width: 86, height: 50))
    button.setTitle("OK", forState: UIControlState.Normal)
    button.setTitleColor(UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1.0), forState: UIControlState.Normal)
    button.addTarget(self, action: "hideSnackBar:", forControlEvents: UIControlEvents.TouchUpInside)
    self.addSubview(button)
}

并使用它:
let snakeView = snake(frame: CGRectMake(0 ,self.view.frame.size.height-66, self.view.frame.size.width, 66)))

并为snakeview设置数据:
snakeView.label.text = "hello"

但是通常我会创建一个函数来更新数据以供查看:
func updateData(title:String){
    self.label.text = title
}

并在需要时调用它:
snake.updateData("hello")

P/s:如果使用xib,则必须实现awakeFromNib而不是init。并使用xib创建蛇(记住设置xib的标识符:“snakeView”):
let snakeView = NSBundle.mainBundle().loadNibNamed("snakeView", owner: nil, options: nil)[0] as snakeView

关于ios - 自定义UIView类-Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33935566/

10-12 02:40