以编程方式添加和更改自定义 UIView (Swift)

Ran*_*rns 5 properties custom-controls uiviewcontroller uiview ios

我正在尝试创建一个可以在其他 UIViewController 中使用的自定义 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我想将它添加到一个单独的 UIViewController 中:

let newView = customView(frame:CGRectMake(0, 0, 500, 400))
self.view.addSubview(newView)
Run Code Online (Sandbox Code Playgroud)

这可以显示视图,但是我需要添加什么才能从嵌入 customView 的 UIViewController 更改属性(例如 myLabel)?

我希望能够从 viewController 访问和更改标签,允许我使用点表示法更改文本、alpha、字体或隐藏标签:

newView.myLabel.text = "changed label!"
Run Code Online (Sandbox Code Playgroud)

现在尝试访问标签会出现错误“‘customView’类型的值没有成员‘myLabel’”

非常感谢您的帮助!

Rei*_*ica 5

这是因为该属性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)
    }
}
Run Code Online (Sandbox Code Playgroud)