UIView

2019-11-22  本文已影响0人  绍清_shao

目录

一般使用

创建

let rect = CGRect(x: 10, y: 10, width: 100, height: 100)
let myView = UIView(frame: rect)

添加

addSubview(_:)
insertSubview(_:aboveSubview:)
insertSubview(_:belowSubview:)
exchangeSubview(at:withSubviewAt:)

View内容需更新

view.setNeedsDisplay()

动画
支持动画的属性有frameboundscentertransformalphabackgroundColor

PS:对View的所有操作要在主线程中

UIView的声明周期

初始化
方法一:init(frame:)代码初始化的时候,一般调用这个函数
方法二:init(coder:)从storyboard或者xib中自定义View,则需要重写这个方法

// 打印信息
setNeedsDisplay()
setNeedsDisplay()
setNeedsLayout()
setNeedsLayout()
init(frame:)
deinit
// 打印信息
willMove(toWindow:)
willMove(toSuperview:)
didMoveToWindow()
didMoveToSuperview()
setNeedsLayout()
layoutSubviews()
// 打印信息
setNeedsLayout()
layoutSubviews()
// 打印信息
 didAddSubview(_:)
 layoutSubviews()
// 打印信息
 willMove(toSuperview:)
 willMove(toWindow:)
 didMoveToWindow()
 didMoveToSuperview()
 removeFromSuperview()

@IBInspectable

// 设置圆角、边框
extension UIView {
    
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    
    @IBInspectable var borderColor: UIColor {
        get {
            return UIColor.init(cgColor: layer.borderColor ??
                UIColor.white.cgColor)
        }
        set {
            layer.borderColor = newValue.cgColor
        }
    }
    
    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
}

添加上面的扩展后可以在storyboard方便设置属性


image.png

后记

如果一个自定义View,没有从xib初始化。然后在storyboard中添加一个View,并把这个View的class设置为自定义的View类型,这个View初始化时不会调用init(frame:),而且调用init(coder:)这个方法。

待完善 storyboard中实时渲染@IBDesignable

参考链接

上一篇 下一篇

猜你喜欢

热点阅读