Keep UIButton Selected/Highlighted after touch(触摸后保持 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 选中/突出显示
- UITextView 内容插图 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- URL编码Swift iOS 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- GPS状态的广播接收器? 2022-01-01