[英]Custom UIView Class - Swift
我已經構建了一個從底部出現並隱藏在一段時間之后的視圖並且它運行良好,但我想在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)
如何從這個類開始我不知道,我用它的框架以編程方式創建視圖,我需要設置按鈕的屬性,例如或標簽,並從任何類創建視圖。
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創建snake(記住xib的set identifier:“snakeView”):
let snakeView = NSBundle.mainBundle().loadNibNamed("snakeView", owner: nil, options: nil)[0] as snakeView
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.