突出显示类似于UIButton的UIView

Jon*_*ner 14 iphone uiviewanimation ios5

我有一个带有许多子视图的UIView和一个被认可的Tap手势,我想模仿它具有"触摸"效果.也就是说,当点击发生时,我想显示容器视图具有不同的背景颜色,并且任何子视图UILabel的文本也看起来突出显示.

当我从UITapGestureRecognizer收到tap事件时,我可以很好地改变背景颜色甚至将UILabel设置为 [label setHighlighted:YES];

由于各种原因,我无法将UIView更改为UIControl.

但是如果我添加一些UIViewAnimation来恢复突出显示,则没有任何反应.有什么建议?

    - (void)handleTapGesture:(UITapGestureRecognizer *)tapGesture {
      [label setHighlighted:YES]; // change the label highlight property

[UIView animateWithDuration:0.20 
                          delay:0.0 
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         [containerView setBackgroundColor:originalBgColor];          
                         [label setHighlighted:NO]; // Problem: don't see the highlight reverted
                     } completion:^(BOOL finished) {                         
                         // nothing to handle here
                     }];    
}
Run Code Online (Sandbox Code Playgroud)

den*_*lor 8

雨燕4

您可以使用这样的自定义视图,例如:

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值,因此它看起来像一个突出显示。


mat*_*att 6

setHighlighted不是可动画视图属性.另外,你说的是两件相反的事情:你将亮度设置为YES而NO设置为同一口气.结果是没有任何反应,因为没有整体变化.

使用完成处理程序或延迟性能稍后更改突出显示.

编辑:

你说"尝试了两个但都没有奏效." 也许你需要澄清延迟表现的意思.我刚试过这个并且它完美地工作:

- (void) tapped: (UIGestureRecognizer*) g {
    label.highlighted = YES;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        label.highlighted = NO;
    });
}
Run Code Online (Sandbox Code Playgroud)

标签必须textColor与其不同,highlightedTextColor以便发生可见的事情.