我有一个带有透明图像的UIButton,其中包含一个用于选中的切换。 在当前配置中,我使用的是系统按钮类型,因为它可以很好地反转按钮。然而,通过这种反转,我得到一个带边框的图像,我希望这个图像填满整个按钮。怎么能实现这一目标?我想从系统中保留透明蒙版。
在下图中是所选系统状态的样子。
答案 0 :(得分:0)
创建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
}
}
}
}
根据您的要求更改颜色
在视图中控制器就像这样
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
}
}