保持UIButton触摸后select/突出显示

我希望我的button在用户点击后保持高亮显示。 如果用户再次点击button,我希望它成为取消/不被强调。 我不知道如何快速做到这一点。 我目前正在使用界面生成器将button突出显示图像和选定的图像设置为相同的.png。

当我运行应用程序并点击button,只要我的手指仍然在button上,它会变成我的高光图像。

使用下面的代码声明isHighLighted作为实例variables

 //write this in your class var isHighLighted:Bool = false override func viewDidLoad() { let button = UIButton(type: .system) button.setTitle("Your title", forState: UIControlState.Normal) button.frame = CGRectMake(0, 0, 100, 44) self.view.addSubview(button as UIView) button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) } func buttonClicked(sender:UIButton) { dispatch_async(dispatch_get_main_queue(), { if isHighLighted == false{ sender.highlighted = true; isHighLighted = true }else{ sender.highlighted = false; isHighLighted = false } }); } 

我会build议使用selected状态,而不是highlighted下面的代码示范与选定的状态

 override func viewDidLoad() { let button = UIButton(type: .system) button.setTitle("Your title", forState: UIControlState.Normal) button.frame = CGRectMake(0, 0, 100, 44) self.view.addSubview(button as UIView) //set normal image button.setImage(normalImage, forState: UIControlState.Normal) //set highlighted image button.setImage(selectedImage, forState: UIControlState.Selected) button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) } func buttonClicked(sender:UIButton) { sender.selected = !sender.selected; } 
 func highlightButton(button: UIButton) { button.highlighted = true } @IBAction func touched(sender: UIButton) { let timer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: self, selector: Selector("highlightButton(sender)"), userInfo: nil, repeats: true) } 
 func buttonPressed(_ sender: UIButton) { // "button" is a property if button.isSelected { button.setImage(UIImage(named: "filled-heart"), for: .normal) button.isSelected = false }else { button.setImage(UIImage(named: "empty-heart"), for: .selected) button.isSelected = true } }