在我的理解, 便利就是参数少或者不需要参数就能使用创建合适的对象, 如UIView的实例。
如下
let initiate = initiatedView(name: "apple")
view.addSubview(initiate)
效果如图:
便利构造.jpg
import UIKit
class initiatedView: UIView {
var targetName: String?
var nameLabel: UILabel = {
let nameLabel = UILabel(frame: CGRect(x: 0, y: 20, width: 100, height: 80))
nameLabel.textAlignment = .center
return nameLabel
}()
//默认已有的函数
override init(frame: CGRect) {
super.init(frame: frame)
}
//默认已有的函数
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//便利构造函数
convenience init(name: String) {
self.init(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
backgroundColor = .blue
targetName = name
addSubview(nameLabel)
nameLabel.text = name
}
}
便利构造函数格式:
使用 convenience关键字
convenience init?(属性:类型){
条件判断结果为否
return nil
*这里要加对self.init的调用
self.init()
*这里进行进一步的操作,可对对象属性赋值
}
网友评论