触摸后保持 UIButton 选中/突出显示

Keep UIButton Selected/Highlighted after touch(触摸后保持 UIButton 选中/突出显示)

本文介绍了触摸后保持 UIButton 选中/突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的按钮在用户点击后保持突出显示.如果用户再次点击该按钮,我希望它被取消选择/不突出显示.我不确定如何快速执行此操作.我目前正在使用界面生成器将按钮突出显示图像和选定图像设置为相同的 .png.

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 about doing this in swift. I'm currently setting the button highlight image and selected image to the same .png using interface builder.

当我运行应用程序并点击按钮时,只要我的手指停留在按钮上,它就会变为我的突出显示图像.

When I run the app and tap the button, it changes to my highlight image for as long as my finger remains on the button.

推荐答案

使用下面的代码将 isHighLighted 声明为实例变量

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

我会推荐使用 selected 状态而不是 highlighted 下面的代码演示选择状态

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

这篇关于触摸后保持 UIButton 选中/突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:触摸后保持 UIButton 选中/突出显示

基础教程推荐