点击时使 UIButton 文本变暗
Posted
技术标签:
【中文标题】点击时使 UIButton 文本变暗【英文标题】:Dim UIButton text when tapped 【发布时间】:2014-05-30 21:36:00 【问题描述】:我正在使用自定义UIButton
s,我想要做的是,当用户触摸按钮时,它会变暗或变成灰色,就像常规按钮一样。
我只是希望文本在用户抬起时暂时改变颜色,因为它会恢复到常规颜色。
我试过这段代码:
button.showsTouchWhenHighlighted = TRUE;
但这只是在它周围形成一个白色圆圈,这不是我想要的。 感谢您的帮助。
【问题讨论】:
对于自定义按钮,您需要手动处理。继承 UIButton 并在 touchesBegan 和 tochesEnd / touchesCancelled 中添加动画。 【参考方案1】:我遇到的最简单的方法是:
[myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];
【讨论】:
【参考方案2】:您可以使用以下UIControlEvents
:
UIControlEventTouchDown
UIControlEventTouchUpInside
UIControlEventTouchUpOutside
像这样适当地为它们分配目标操作方法:
//when touch initiated
[myButton addTarget:self
action:@selector(buttonTouchStartAct:)
forControlEvents:UIControlEventTouchDown];
//on touch released outside button bounds
[myButton addTarget:self
action:@selector(buttonTouchEndAct:)
forControlEvents:UIControlEventTouchUpOutside];
//on touch released while still inside button bounds (most commonly used)
[myButton addTarget:self
action:@selector(buttonAct:)
forControlEvents:UIControlEventTouchUpInside];
-(void)buttonTouchStartAct:(UIButton *)sender
[sender.titleLabel setTextColor:[UIColor redColor]];
-(void)buttonTouchEndAct:(UIButton *)sender
[sender.titleLabel setTextColor:[UIColor greenColor]];
-(void)buttonAct:(UIButton *)sender
//touch ended in this case too
[self buttonTouchEndAct:sender];
//...
//your main button logic
//...
【讨论】:
【参考方案3】: //when touch initiated
[myButton addTarget:self
action:@selector(buttonTouchStartAct:)
forControlEvents:UIControlEventTouchDown];
//on touch released outside button bounds
[myButton addTarget:self
action:@selector(buttonTouchEndAct:)
forControlEvents:UIControlEventTouchUpOutside];
//on touch released while still inside button bounds (most commonly used)
[myButton addTarget:self
action:@selector(buttonAct:)
forControlEvents:UIControlEventTouchUpInside];
然后在方法内部改变按钮的颜色
【讨论】:
【参考方案4】:尝试像这样在单击按钮时更改标题标签的 alpha
- (IBAction)buttonClick:(id)sender
UIButton *button = sender;
[UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveEaseInOut animations:^
[button.titleLabel setAlpha:0.5];
completion:^(BOOL finished)
[button.titleLabel setAlpha:1];
];
【讨论】:
以上是关于点击时使 UIButton 文本变暗的主要内容,如果未能解决你的问题,请参考以下文章
当用户与 UIButton 交互时,是不是可以让我在自定义 UIButton 的 drawRect 中绘制的内容“变暗”?