微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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 举报,一经查实,本站将立刻删除。