【问题标题】:Swift assign text to label in xib fileSwift将文本分配给xib文件中的标签
【发布时间】:2015-10-28 06:55:53
【问题描述】:

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

(注意:将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
    }
}

我在某处制作自定义视图:

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 写一个扩展并添加一个分配文本的函数吗?

【问题讨论】:

    标签: ios swift initialization xib custom-view


    【解决方案1】:

    你必须从 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)
    

    【讨论】:

      猜你喜欢
      • 2014-08-13
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多