ios – 自定义UIView类 – Swift

前端之家收集整理的这篇文章主要介绍了ios – 自定义UIView类 – 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,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,alpha: 1.0)


    label = UILabel(frame: CGRect(x: 12,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,height: 50))
    button.setTitle("OK",forState: UIControlState.Normal)
    button.setTitleColor(UIColor(red: 76/255,forState: UIControlState.Normal)
    button.addTarget(self,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
原文链接:https://www.f2er.com/iOS/334678.html

猜你在找的iOS相关文章