iOS-UIButton系统选择图像

标签 ios swift uibutton

我有一个带有透明图像的 UIButton,带有用于选择的切换开关。 在当前配置中,我使用系统按钮类型,因为它可以很好地反转按钮。然而,通过这种反转,我得到了一个带有边框的图像,并且我希望该图像填充整个按钮。如何才能实现这一目标?我想保留系统中的透明蒙版。

Here is the repository.

下图中是所选系统状态的样子。

enter image description here

最佳答案

创建 UIButton 的子类并覆盖 isSelected

例如

  class CustomButton: UIButton {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */




    override var isSelected: Bool {


        didSet {
            if isSelected {
                self.backgroundColor = UIColor.blue
                self.tintColor = UIColor.white
            } else {
                self.backgroundColor = .white
                self.tintColor = UIColor.red
            }

        }
    }

}

根据您的要求更改颜色

在 View Controller 中这样做

class ViewController: UIViewController {

@IBOutlet weak var button: CustomButton!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    button.isSelected = false
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func btnTapped(_ sender: Any) {
    button.isSelected = !button.isSelected
}

}

还有一件事你必须将图像的渲染选项设置为模板 Template Image

关于iOS-UIButton系统选择图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46707788/

相关文章:

objective-c - “发送到实例的无法识别的选择器”?

ios - 避免 UIImage 的 imageNamed - 内存管理

Swift UIActivityViewController 电子邮件主题行继承全局 UINavigationBar 字体更改

ios - 在交互式通知中使用变量而不是字符串

ios - 使用自定义按钮类调用特定 View Controller

ios - UIButton 未注册触摸

ios touch 从一个按钮移动到另一个按钮

ios - 使用数组在 UITableView 中具有不同标签颜色的不同单元格

objective-c - 以编程方式创建 View

iphone - 如何知道 Pubnub 中的退订 channel 请求是否成功?