首页 > 解决方案 > 从另一个类调用自定义 UIView 中的 IBOutlet

问题描述

我正在寻找一种方法来从另一个类中引用自定义类 UIView 中的 IBOutlet 变量。我发现layoutSubviews,但每次更改仅适用于第一次通话,而不适用于每次后续通话。感谢帮助!

ViewController class:

var SB = StatusBar()
SB.update(1)
SB.update(2)
SB.update(3)

StatusBar class:
class StatusBar: UIView {

    @IBOutlet var view: UIView!
    @IBOutlet weak var label: UILabel!
     
    var ActualStatus: Int!

    required init?(coder: NSCoder) {

        super.init(coder: coder)
        xibSetup()
       
    
    }
    
    override init(frame: CGRect) {

        super.init(frame: frame)
        xibSetup()
     
    }
     

    func update(status) {
        ActualStatus = status
        self.layoutSubviews()
    }

 
    override func layoutSubviews() {
           super.layoutSubviews()
 
        label.text = ActualStatus

    }


    func xibSetup() {
        
        
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
        addSubview(view)
        
        
    }
    
    func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of:self))
        let nib = UINib(nibName: "StatusBar", bundle: bundle)
        
   
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        return view
    }
}

结果:label.text 为 1,更改仅适用于第一次调用

标签: swiftxcode

解决方案


推荐阅读