t0a*_*0a0 6 highlight uibutton uiview
当用户触摸UIButton时,它会变灰.什么苹果能做到这样的效果?当我的自定义UIButton突出显示时,我需要相同的效果.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
if ([keyPath isEqualToString:@"highlighted"]){
UIButton *button = object;
if (button.isHighlighted) {
self.backgroundColor=[UIColor colorWithRed:36.0/255.0 green:153.0/255.0 blue:116.0/255.0 alpha:1];
}else{
self.backgroundColor=appDelegate.currentAppColor;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用此代码,但更改背景颜色不会影响任何子视图.我也需要它们变灰.
den*_*lor 17
例如,您可以使用这样的自定义视图:
class HighlightView: UIView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
DispatchQueue.main.async {
self.alpha = 1.0
UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveLinear, animations: {
self.alpha = 0.5
}, completion: nil)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
DispatchQueue.main.async {
self.alpha = 0.5
UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveLinear, animations: {
self.alpha = 1.0
}, completion: nil)
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
DispatchQueue.main.async {
self.alpha = 0.5
UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveLinear, animations: {
self.alpha = 1.0
}, completion: nil)
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它来代替,UIView每当你点击它时,它都会改变它的alpha值,所以它看起来像一个亮点。
我认为没有一个简单或明确的答案.
免责声明:这个答案中的所有代码都是从我的头脑中写的,所以请原谅我的错误.
我建议做这样的事情:
建议1:降低所有视图的子视图的不透明度,这不会影响颜色......
-(void)buttonTouched{
for(UIView *subview in self.subviews){
subview.alpha = 0.5;
}
}
Run Code Online (Sandbox Code Playgroud)
建议2(未经测试):尝试通过手动进行覆盖所有子视图(缺点:你必须手动设置颜色,如果它不是单色的,那将是疯狂的):
-(void)buttonTouched{
for(UIView *subview in self.subviews){
if([subview respondsToSelector:@selector(setBackgroundColor:)]){
//for generic views - changes UILabel's backgroundColor too, though
subview.backgroundColor = [UIColor grayColor];
}
if([subview respondsToSelector:@selector(setTextColor:)]){
//reverse effect of upper if statement(if needed)
subview.backgroundColor = [UIColor clearColor];
subview.textColor = [UIColor grayColor];
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是非常糟糕的设计,可能会导致很多问题,但它可能会对您有所帮助.上面的例子需要很多改进,我只是想给你一个提示.你必须恢复touchesEnded:方法中的颜色.也许它可以帮助你......
建议3:用透明视图覆盖整个视图(如果是矩形)
-(void)buttonTouched{
UIView *overlay = [[UIView alloc]initWithFrame:self.bounds];
overlay.backgroundColor = [[UIColor grayColor]colorWithAlphaComponent:0.5];
[self addSubview: overlay];
}
Run Code Online (Sandbox Code Playgroud)
当用户松开手指时,您必须将其删除.
建议4:另一个选择是创建当前视图的位图并根据自己的喜好修改像素,这是相当多的工作,所以我将在这里省略代码.
Apple可能会将最后两款混合使用.当触摸按钮时,它将覆盖像素并在具有alpha分量的每个像素上覆盖灰色像素.
我希望我能帮忙.