ios - Swift 将文本分配给 xib 文件中的标签

标签 ios swift initialization xib custom-view

我的项目中有一个连接到 CustomView.xib 的 CustomView.swift (UIView 的子类)。

(注意:将xib类设置为CustomView但没有设置所有者)

CustomView.swift中加载xib文件:

class CustomView: UIView {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }*/

    override init(frame: CGRect) {
        super.init(frame: frame)
        let subView: UIView = loadViewFromNib()
        subView.frame = self.bounds
        //label1.text = "123" //would cause error
        addSubview(subView)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func loadViewFromNib() -> UIView {
        let view: UIView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
        return view
    }
}

我在某个地方制作自定义 View :

let myCustomView:CustomView = CustomView.init(frame: CGRectMake(0, 0, 100, 100))
myCustomView.label1?.text = "123"
myCustomView.label2?.text = "abc"
print(myCustomView.label1.text)// returned nil

xib 标签上没有显示任何内容。

我应该为 CustomView.swift 编写一个扩展并添加一个分配文本的函数吗?

最佳答案

您必须从 Nib 加载

//let myCustomView:CustomView = CustomView.init(frame: CGRectMake(0, 0, 100, 100))
let myCustomView:CustomView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! CustomView

myCustomView.label1?.text = "123"
myCustomView.label2?.text = "abc"
print(myCustomView.label1.text)

关于ios - Swift 将文本分配给 xib 文件中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33384725/

相关文章:

html - iOS 将不可见的 Unicode 字符显示为包含 “mvs” 的虚线框

ios - 在 Github Actions iOS 项目设置过程中,进程已完成,退出代码为 66

ios - 带有部分和带有页眉和页脚的行的可折叠表格 View

ios - 在 UISplitViewController 应用程序中从 DetailViewController 获取 MasterViewController

swift - 使用 rxSwift 的简单计时器

c - C 语言第 2 级数组的理想数据类型

arrays - 不能在属性初始值设定项中使用实例成员 'country';属性初始值设定项在 'self' 可用之前运行

ios - 如何从 iOS 键盘扩展中检测到通过在 iMessage 中点击 "Send"等操作清除了文本字段?

swift - 使用外部源的整数更新标签

python - 什么是 wrapper_descriptor,为什么 Foo.__init__() 在这种情况下是一个?