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 选中/突出显示
基础教程推荐
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01