【问题标题】:How to set a default title in UIButton subclass that works in Interface Builder (Xcode 9)如何在界面生成器(Xcode 9)中工作的 UIButton 子类中设置默认标题
【发布时间】:2018-05-22 05:24:20
【问题描述】:

我有一个在整个应用程序中重复出现的按钮,因此我创建了一个子类以避免每次都必须设置所有基本属性。

我可以设置背景颜色、文本颜色、圆角。

但是,当我尝试设置默认标题时,事情就崩溃了——不是“按钮”。 在 Interface Builder 中,它会忽略标题,但也会忽略字体颜色,这在我不设置标题时有效。

如果我运行应用程序,一切看起来都很好,但使用 Interface Builder 的一大要点是省去不断运行应用程序以检查基本 UI 布局的步骤。

这是子类。 请注意,如果您注释掉 2 个 setTitle 行,按钮会显示正确的文本颜色(白色)。

import UIKit

@IBDesignable class ContinueButton: UIButton {

    @IBInspectable var titleColour: UIColor = .white {
        didSet {
            setTitleColor(titleColour, for: .normal)
        }
    }

    @IBInspectable var bgColour: UIColor = UIColor.gray {
        didSet {
            backgroundColor = bgColour
        }
    }

    @IBInspectable var buttonTitle: String = "Continue" {
        didSet {
            setTitle(buttonTitle, for: .normal)
        }
    }

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

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

    public func setAttributes() {
        setTitleColor(titleColour, for: .normal)
        backgroundColor = bgColour
        setTitle(buttonTitle, for: .normal)
    }

    override public func layoutSubviews() {
        super.layoutSubviews()

        setAttributes()

        layer.cornerRadius = 0.5 * bounds.size.height
        clipsToBounds = true
    }
}

ps,我的主要目标是创建一个可重用的自定义按钮,负责设置一堆默认值。如果有更好的方法来实现这一点,我会很高兴听到这个消息 - 特别是如果它可以通过视觉而不是通过代码来完成。

感谢您提供的任何建议,

-妮可

【问题讨论】:

  • 首先,你为什么要重命名东西?使用backgroundColor 等。不要重新发明轮子!(您已经继承了UIButton。)其次,您是否将 IB(或情节提要)按钮设置为实际 ContinueButton?最后,如果您需要我所说的示例,请参考我对此的回答:stackoverflow.com/questions/42041809/… 基本上,子类,设置 IBDesignable/IBInspectable,并公开 - 使用已经建立的属性 - 你需要什么。
  • 我正在重命名,因为(根据错误消息)您不能覆盖变量然后为其设置初始值。您展示的示例访问 Layer 中的相同命名变量,而不是直接在 UIButton 中。
  • 是的,我确实设置了按钮类 - 没有它,最终结果看起来不像我的示例图片。澄清一下 - 我试图使用子类来避免在 IB 中创建的每个按钮中设置所有属性。我在图片中展示的示例仅使用了子类设置的属性 - 我没有在 IB 中自定义该按钮。

标签: ios swift uibutton interface-builder subclass


【解决方案1】:

只需覆盖 prepareForInterfaceBuilder() 并添加 setAttributes()。

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    setAttributes()
}

【讨论】:

  • 这对 OP 面临的问题有何帮助?
  • 为什么要投反对票!请参考developer.apple.com/documentation/objectivec/nsobject/…。 “当 Interface Builder 使用 IB_DESIGNABLE 属性实例化一个类时,它会调用此方法让生成的对象知道它是在设计时创建的。”
  • 这没有任何效果。它像以前一样显示在 IB 中,带有蓝色的“按钮”标题。
  • 这很奇怪。这确实适用于我的 Mac(Xcode 版本 9.2)。您能否尝试重新加载情节提要或重新启动 Xcode。
【解决方案2】:

tintColor 属性可以解决问题。 button.tintColor = UIColor.red

但要确保覆盖prepareForInterfaceBuilder()

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    button.tintColor = UIColor.red
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    相关资源
    最近更新 更多