ios - 如何在设计器中的自定义按钮控件上显示图像

标签 ios swift uibutton interface-builder ibdesignable

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

@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)
    }

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

enter image description here

最佳答案

亚历克斯给你指出的答案 - 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)
    }

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

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

否则,您的图像资源就会出现问题。

关于ios - 如何在设计器中的自定义按钮控件上显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147756/

相关文章:

ios - 在进行最小滚动或点击之前,单元格不会显示在表格 View 中(注意 : nothing happens on a background thread)

ios - 旋转时自动调整 UITableView 的大小,宽度灵活

swift - UIButton 中的图像和标题

ios - 当用户按下主页按钮时,使用 alpha 暂停和恢复 UIView 动画不起作用

ios - 在 Swift 中顺序执行任务

ios - Facebook 登录 - 仅请求电子邮件,而不请求个人资料图片、姓名等

ios - 应用程序可以在模拟器上完美运行,但不能在物理设备上运行[在 iOS 13.3.1 上]

iphone - 如何在 iPhone 的 UIWebview 上显示 html 字符串?

ios - ViewController 出现两次过渡

ios - 在 Swift 中使用 UIButton 动画