问题描述
我希望我的按钮在用户点击后保持突出显示。如果用户再次点击该按钮,我希望它变为取消选择/不突出显示。我不确定如何快速做到这一点。我目前正在使用界面构建器将按钮高亮图像和所选图像设置为相同的.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
}
});
}
我建议使用选择
州而不是突出显示
以下代码显示选定状态
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选中/突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!