Keep UIButton Selected/Highlighted after touch

后端 未结 5 1494
北荒
北荒 2020-12-24 15:14

I\'d like my button to remain highlighted after the user taps it. If the user taps the button again I\'d like it to become de-selected/unhighlighted. I\'m not sure how to go

5条回答
  •  别那么骄傲
    2020-12-24 15:42

    Use below code declare isHighLighted as instance variable

    //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
            }
         });
    }
    

    I would recomend to use selected state instead of highlighted the below code demonstarate with selected state

    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;
    }
    

提交回复
热议问题