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

kmpatx3s  于 2023-08-08  发布在  iOS
关注(0)|答案(2)|浏览(148)

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

newView.myLabel.text = "changed label!"


尝试访问标签现在会出现错误“类型'customView'的值没有成员'myLabel'”
非常感谢你的帮助!

2fjabf4q

2fjabf4q1#

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

字符串

xtupzzrd

xtupzzrd2#

简单点!

import UIKit
import WebKit

class CustomWebView: UIView {
    var webview = WKWebView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        webview.frame = bounds
        addSubview(webview)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(frame: .zero)
    }
    
    func loadWebView(with urlString: String) {
        guard let request = URLRequest(url:URL(string: urlString)) else { return }
        webview.load(request)
    }
}

字符串
要访问它,

let customView = CustomWebView(frame: view.bounds)
customView.loadWebView(with: "https://www.google.com/")

相关问题