【问题标题】:@IBDesignable not showing background color in IB@IBDesignable 未在 IB 中显示背景颜色
【发布时间】:2017-02-23 16:16:44
【问题描述】:

我有一个 UIView 如下:

import UIKit

@IBDesignable
class CHRAlertView: UIView {

    @IBOutlet var icon:UILabel!
    @IBOutlet var alertText:UITextView!

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initialize()
    }

    private func initialize(){
        self.backgroundColor = UIColor.green
    }

}

根据@IBDesignable 的工作原理,这应该以绿色背景显示在 IB 中,但我得到了这样的清晰颜色:

为什么没有按预期运行?我需要根据 @IBDesignable 中设置的默认值在 IB 中显示背景颜色。

【问题讨论】:

    标签: uiview interface-builder xcode8 ibdesignable


    【解决方案1】:

    由于backgroundColor 不是通过@IBInspectable 创建的IB 属性,它似乎总是覆盖init 或draw 方法中的任何内容。意思是,如果它在 IB 中是“默认”的,它会导致它被 nil 覆盖。但是,如果在 prepareForInterfaceBuilder 方法中设置 backgroundColor 可以在 IB 中工作并显示。因此,可以合理地假设backgroundColor 必须在运行时设置。为此,我有以下内容:

    //------------------
        //Setup and initialization
        //------------------
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            self.initialize()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            self.initialize()
        }
    
        //Setups content, styles, and defaults for the view
        private func initialize(){
            self.staticContent()
            self.initStyle()
        }
    
        //Sets static content for the view
        private func staticContent() {
    
        }
    
        //Styles the view's colors, borders, etc at initialization
        private func initStyle(){
    
        }
    
        //Styles the view for variables that must be set at runtime
        private func runtimeStyle(){
            if self.backgroundColor == nil {
                self.backgroundColor = UIColor.green
            }
        }
    
        override func prepareForInterfaceBuilder() {
            self.runtimeStyle()
        }
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
            self.runtimeStyle()
        }
    

    如果它在 IB 中为“默认”(读取 nil),则默认 backgroundColor 为一种颜色,但如果在 IB 中设置了 backgroundColor,则不使用 UIColor.green,这正是我所需要的。

    在#swift-lang irc 中向 Eridius 大喊帮助我得到这个答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-06
      • 2011-06-02
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2013-02-05
      相关资源
      最近更新 更多