我有一个带有透明图像的 UIButton,带有用于选择的切换开关。 在当前配置中,我使用系统按钮类型,因为它可以很好地反转按钮。然而,通过这种反转,我得到了一个带有边框的图像,并且我希望该图像填充整个按钮。如何才能实现这一目标?我想保留系统中的透明蒙版。
下图中是所选系统状态的样子。
最佳答案
创建 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
}
}
关于iOS-UIButton系统选择图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46707788/