如何在 swift 中的 xib / NIB 中设置变量

问题描述

无法修改我的 XIB 类中变量的值。如何从 ViewController 的 didLoad 设置变量 var orientation 的值?我总是只打印我在类中设置的初始认值 .none

在我的 VC 中

override func viewDidLoad() {
        super.viewDidLoad()
                    
        self.myTestCustomView.orientation = .square
       
    }

我的课

enum Orientation: String,CaseIterable {
    case none
    case horizontalRectangle,verticalRectangle,square
}

class CustomView : UIView {
    @IBOutlet private var contentView:UIView?
    // other outlets
    
    private var _orientation: Orientation = .none
    var orientation: Orientation {
        set { _orientation = newValue }
        get {return _orientation}
    }
    
    override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        self.commonInit()
    }
    
    required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
        super.init(coder: aDecoder)
        self.commonInit()
    }
    
    private func commonInit() {
        Bundle.main.loadNibNamed("CustomView",owner: self,options: nil)
        guard let content = contentView else { return }
        content.frame = self.bounds
        content.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        self.addSubview(content)
        
        print("checkValue\(_orientation.rawValue)")
        
        self.setNeedsLayout()

    }
}

编辑:

我的解决方案,删除_orientation,从 VC 直接访问 orientation。欢迎任何建议或意见。

var orientation: Orientation {

  set {
        switch newValue {
        case .horizontalRectangle:
            self.contentView.layer.cornerRadius = self.frame.height / 5.0 //height since is orizzontal rectangle
        case .verticalRectangle:
            self.contentView.layer.cornerRadius = self.frame.width / 5.0
        case.square:
            self.contentView.layer.cornerRadius = self.frame.width / 5.0
        case .none:
            self.contentView.layer.cornerRadius =  0.0
        }
        self.setNeedsLayout()
    }
    
    get {return self.orientation}

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)