我希望我的按钮在用户点击后保持突出显示。如果用户再次点击按钮,我希望它被取消/不被强调。我不知道如何快速做到这一点。我目前使用界面构建器将按钮突出显示图像和选定图像设置为相同的.png。保持UIButton触摸后选中/突出显示
当我运行该应用程序并点击该按钮时,只要我的手指保持在按钮上,它就会更改为我的高光图像。
我希望我的按钮在用户点击后保持突出显示。如果用户再次点击按钮,我希望它被取消/不被强调。我不知道如何快速做到这一点。我目前使用界面构建器将按钮突出显示图像和选定图像设置为相同的.png。保持UIButton触摸后选中/突出显示
当我运行该应用程序并点击该按钮时,只要我的手指保持在按钮上,它就会更改为我的高光图像。
使用下面的代码 声明isHighLighted
作为实例变量
//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
下面的代码demonstarate与选择的状态
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;
}
func highlightButton(button: UIButton) {
button.highlighted = true
}
@IBAction func touched(sender: UIButton) {
let timer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: self, selector: Selector("highlightButton(sender)"), userInfo: nil, repeats: true)
}
func buttonPressed(_ sender: UIButton) {
// "button" is a property
if button.isSelected {
button.setImage(UIImage(named: "filled-heart"), for: .normal)
button.isSelected = false
}else {
button.setImage(UIImage(named: "empty-heart"), for: .selected)
button.isSelected = true
}
}
我没有看到您在代码中声明“isHighLigthed”的地方。我看到你正在检查“isHighLighted”的值,但不是你实际声明的值。 – dcbenji
在class Abc {'line'var isHighLighted:Bool = false''后面声明。这将完美工作 – codester
@ user3822654你van也使用selected状态,因为它更多地用于切换行为。您需要为'selectedState'的'normalState'设置两个图像。希望这有助于 – codester