OGeek|极客世界-中国程序员成长平台

标题: ios - 以编程方式添加和更改自定义 UIView (Swift) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:12
标题: ios - 以编程方式添加和更改自定义 UIView (Swift)

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

自定义 View :

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)

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

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

newView.myLabel.text = "changed label!"

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

非常感谢您的帮助!



Best Answer-推荐答案


这是因为属性 myLabel 未在类级别声明。将属性声明移动到类级别并将其标记为公共(public)。然后,您将能够从外部访问它。

类似

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)
    }
}

关于ios - 以编程方式添加和更改自定义 UIView (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080434/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4