【问题标题】:keep the original color of the UIButton's icon when it's tapped in Swift在 Swift 中点击时保持 UIButton 图标的原始颜色
【发布时间】:2022-09-27 11:04:02
【问题描述】:

我正在努力在 Swift 中制作自定义 UIButton,并且有一个关于使用 custom 类型初始化 UIButton 的问题。

这是我项目中当前自定义按钮的图像,当用户点击按钮时,原始颜色为.whilte 的图像图标变灰。但是,即使用户点击按钮并且按钮状态发生变化,我也希望将图像颜色保持为白色。我想我应该用自定义类型初始化按钮,但是当我尝试用init(type: UIButton.ButtonType) 初始化时,我收到了类似Must call a designated initializer of the superclass \'UIButton\' 的消息,所以有人可以指点我正确的方向吗?

这是自定义按钮类的代码。

import UIKit

class MyCapsuleButton: UIButton {

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

    required init?(coder: NSCoder) {
        fatalError(\"init(coder:) has not been implemented\")
    }

    init(backgroundColor: UIColor, title: String, textColor: UIColor) {
        super.init(frame: .zero)
        // super.init(type: .custom) -> tried to initialize with type, but didn\'t work
        self.backgroundColor = backgroundColor
        self.setTitle(title, for: .normal)
        self.setTitleColor(textColor, for: .normal)
        configure()
    }

    func configure() {
        translatesAutoresizingMaskIntoConstraints = false
        titleLabel?.font = UIFont.customNormal()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.frame.height / 2
    }
}

我称之为

lazy var deletionButton: MyCapsuleButton = {
    let button = MyCapsuleButton(backgroundColor: .Red(), title: \"DELETE\", textColor: .white)
    button.setImage(Images.delete, for: .normal)
    return button
}()

我阅读了文档,上面写着You specify the type of a button at creation time using the init(type:) method,我想我需要在自定义初始化程序中调用super.init(type: .custom),但是我在情节提要上收到了“必须调用...”错误。另外,我没有在这个项目中使用故事板,我想知道如何使用一些自定义初始化参数(如背景颜色、标题、文本颜色)调用自定义类型。


稍后添加这部分...

因此,似乎当我创建 UIButton 的子类时,默认情况下该类型将是自定义的。 (我打印了类型并弄清楚了。)

那么设置 button.setImage(Images.delete, for: .normal) 是否会使垃圾图标变灰?

  • 有一个属性叫做adjustsImageWhenHighlighted,设置为NO
  • @guru 啊……你是对的。我将 adjustsImageWhenHighlighted 设置为否,一切正常。我太初学者了。不过还是谢谢你。
  • 顺便说一句,它说 adjustsImageWhenHighlighted 将在 ios15 中被弃用,但你知道做同样事情的新方法吗?
  • 对于使用 ConfigurationUpdateHandle,请在 sarunw.com/posts/dynamic-button-configuration 上阅读更多相关信息

标签: ios swift uibutton


【解决方案1】:

启用突出显示调整图像 (adjustsImageWhenHighlighted) 选项后,按钮图像在突出显示状态时会变暗。 因此,您应该关闭该属性,如下所示。

button.adjustsImageWhenHighlighted = false

或者,您可以使用情节提要关闭。 https://i.stack.imgur.com/N42m4.png

【讨论】:

    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 2012-02-13
    • 2015-06-02
    • 1970-01-01
    • 2021-12-05
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多