【问题标题】:Adding and changing a custom UIView programmatically (Swift)以编程方式添加和更改自定义 UIView (Swift)
【发布时间】:2015-12-04 03:28:07
【问题描述】:

我正在尝试创建一个可以在其他 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 访问和更改标签,允许我更改文本、alpha、字体或使用点表示法隐藏标签:

newView.myLabel.text = "changed label!"

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

非常感谢您的帮助!

【问题讨论】:

    标签: ios uiview uiviewcontroller properties custom-controls


    【解决方案1】:

    这是因为属性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,它将字符串作为参数,然后在内部设置标签字符串。这个函数也应该是公开的。
    • 尝试像在您的示例中那样在类声明中放置一个“公共”语句,Xcode 将单词 public 视为一个单独的语句,因为它错误“一行上的连续声明必须由';'
    • 知道了!我必须将类声明为 public,然后将任何变量或函数声明为 public(使用“public var”而不是 public),并将 init?(coder) 函数声明为 public 以使其工作。跨度>
    • @RanLearns 很高兴知道它对您有用。如果有帮助,请投票/接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2020-02-19
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多