我正在尝试创建一个可以在其他UIViewControllers中使用的自定义UIView。
自定义视图:
import UIKit
class customView: UIView {
override init(frame: CGRect) {
super.init(frame:frame)
let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 100))
addSubview(myLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
然后我想将它添加到一个单独的UIViewController:
let newView = customView(frame:CGRectMake(0, 0, 500, 400))
self.view.addSubview(newView)
这可以显示视图,但是我需要添加什么才能从嵌入customView的UIViewController更改属性(例如myLabel)?
我希望能够从viewController访问和更改标签,允许我使用点表示法更改文本,字母,字体或隐藏标签:
newView.myLabel.text = "changed label!"
现在尝试访问标签会出现错误“类型'值'customView'没有成员'myLabel'”
非常感谢您的帮助!
答案 0 :(得分:4)
这是因为属性myLabel
未在类级别声明。将属性声明移动到类级别并将其标记为公共。然后你就可以从外面访问它了。
像
这样的东西import UIKit
class customView: UIView {
public myLabel: UILabel?
override init(frame: CGRect) {
super.init(frame:frame)
myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 100))
addSubview(myLabel!)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}