Быстро назначить текст метке в xib-файле

У меня есть CustomView.swift (подкласс UIView), связанный с CustomView.xib в моем проекте.

(примечание: установите класс xib в CustomView, но не установите владельца)

Загрузите файл xib в CustomView.swift:

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 и добавить функцию, назначающую текст?

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)
Другие вопросы по тегам