【问题标题】:How to show image on custom button control in designer如何在设计器中的自定义按钮控件上显示图像
【发布时间】:2019-08-04 11:26:03
【问题描述】:

我有一个自定义按钮控件,我试图在其中显示按钮的图像,但尽管以编程方式定义它,但它没有出现。

@IBDesignable class UCButtonNext: UIButton {
    // setup programatically
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()
    }

    // setup via Storyboard
    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupButton()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        setupButton()
    }

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

    func setupButton() {
        setupButtonStyle()
        setupShadow()
    }

    func setupButtonStyle() {
        setTitleColor(.white, for: .normal)

        backgroundColor         = UIColor.clear
        titleLabel?.font        = UIFont(name: "Courier", size: 18)
        setTitleColor(UIColor.black, for: .normal)

        layer.cornerRadius      = frame.height / 2
        layer.borderWidth       = 1.0
        layer.borderColor       = UIColor.white.cgColor

        setImage(UIImage(named: "btnArrowRight"), for: .normal)
    }

我的按钮显示在设计器中,但似乎无法显示图像。

【问题讨论】:

  • 似乎除了设置图像外一切正常,所以我会检查项目以查看图像是否存在并正确导入。

标签: ios swift uibutton interface-builder ibdesignable


【解决方案1】:

Alex 向您指出的答案 - https://stackoverflow.com/a/40359161/10657724 - 应该是您所需要的。

为了帮助您调试问题,请更改此行:

setImage(UIImage(named: "btnArrowRight"), for: .normal)

到:

    // DYNAMIC BUNDLE DEFINITION FOR DESIGNABLE CLASS
    let dynamicBundle = Bundle(for: type(of: self))

    // AND THEN SUCCESSFULLY YOU CAN LOAD THE RESSOURCE
    if let image = UIImage(named: "btnArrowRight", in: dynamicBundle, compatibleWith: nil) {
        setImage(image, for: .normal)
        setTitle("Works!", for: .normal)
    } else {
        setTitle("Failed!", for: .normal)
    }

这会将按钮的标题设置为“有效!”或“失败!”

如果您看到“有效!”您还应该看到您的图像。

否则,你的图片资源有问题。

【讨论】:

    【解决方案2】:

    这个问题的答案可能会有所帮助:

    https://stackoverflow.com/a/40359161/10657724

    您需要在创建图像时动态指定捆绑包,因为主捆绑包在设计时不可用。

    【讨论】:

    • 我在这个例子中都试过了,但似乎都不管用。此外,图像不会在模拟器模式或运行模式下的手机上显示。 '// 试过这个 // let image = UIImage(named: "btnArrowRight", in: Bundle(for: type(of: self)), compatibleWith: traitCollection) // setImage(image, for: .normal) // 试过this // let dynamicBundle = Bundle(for: type(of: self)) // let image = UIImage(named: "btnArrowRight", in: dynamicBundle, compatibleWith: nil) // setImage(image, for: .normal)'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2011-07-17
    • 2023-03-11
    相关资源
    最近更新 更多