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

Ios 以编程方式添加和更改自定义UIView(Swift),ios,uiview,uiviewcontroller,properties,custom-controls,Ios,Uiview,Uiviewcontroller,Properties,Custom Controls,我正在尝试创建一个自定义UIView,可以在其他UIViewController中使用 自定义视图: 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))

我正在尝试创建一个自定义UIView,可以在其他UIViewController中使用

自定义视图:

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”


非常感谢你的帮助

这是因为属性
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)
    }
}

在这种情况下,我建议您在customView中声明一个函数,
updateText
,它将字符串作为参数,然后在内部设置标签字符串。此func也应该是公共的。尝试在类声明中放入“public”语句,如您的示例中所示,Xcode将单词public视为一个单独的语句,因为它错误“一行上的连续声明必须用“;”分隔”知道了!我必须将a类声明为public,然后将任何变量或函数声明为public(使用“public var”而不是public),并将init?(coder)函数声明为public以使其工作。@很高兴知道它适合您。如果有帮助,请投票/接受答案。