突出显示类似于 UIButton 的 UIView

发布于 2024-12-24 23:50:10 字数 1011 浏览 1 评论 0原文

我有一个带有多个子视图的 UIView 和一个可识别的关联点击手势,我想模仿它具有“触摸”效果。也就是说,当点击发生时,我想显示容器视图具有不同的背景颜色,并且任何子视图 UILabels 的文本也看起来突出显示。

当我从 UITapGestureRecognizer 收到点击事件时,我可以很好地更改背景颜色,甚至将 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
                     }];    
}

I have a UIView with a number of subviews and a Tap gesture recognized associated and I want to mimic it having a 'touch' effect. That is, when the tap happens, I want to show the container view to have a different background color and the text of any subview UILabels to also look highlighted.

When I receive the tap event from UITapGestureRecognizer, I can change the background color just fine and even set the UILabel to [label setHighlighted:YES];

For various reasons, I cannot change the UIView to UIControl.

But if I add some UIViewAnimation to revert the highlighting, nothing happens. Any suggestions?

    - (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
                     }];    
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

同尘 2024-12-31 23:50:10

Swift 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)
        }
    }
}

只需随意调整持续时间和动画即可。最后,您可以使用它来代替 UIView,并且每当您单击它时,它都会更改其 alpha 值,因此它看起来像一个突出显示。

Swift 4

You can use a custom view like this for example:

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)
        }
    }
}

Just play around with the duration and animations as you like. In the end you can use it instead of UIView and whenever you will click on it, it will change its alpha value so it will look like a highlight.

傾城如夢未必闌珊 2024-12-31 23:50:10

setHighlighted 不是可动画化的视图属性。另外,您说的是两个相反的事情:您同时将突出显示设置为“是”和“否”。结果将是什么也没有发生,因为没有整体变化。

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

编辑:

你说“都尝试过,但都不起作用”。也许您需要澄清我所说的延迟性能的含义。我刚刚尝试过这个,它工作得很好:

- (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;
    });
}

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

setHighlighted isn't an animatable view property. Plus, you're saying two opposite things: you setHighlighted to YES and NO in the same breath. The result will be that nothing happens because there's no overall change.

Use the completion handler or delayed performance to change the highlight later.

EDIT:

You say "tried both but neither worked." Perhaps you need clarification on what I mean by delayed performance. I just tried this and it works perfectly:

- (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;
    });
}

The label must have a different textColor vs its highlightedTextColor so that something visible happens.

别挽留 2024-12-31 23:50:10

简单的解决方案是覆盖点击手势识别器
如下所示:

Swift 4.x

class TapGestureRecognizer: UITapGestureRecognizer {
    var highlightOnTouch = true

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)

        if highlightOnTouch {
            let bgcolor = view?.backgroundColor
            UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
                self.view?.backgroundColor = .lightGray
            }) { (_) in
                UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
                    self.view?.backgroundColor = bgcolor
                })
            }
        }
    }

}

Simple solution is override tap gesture regognizer
like below:

Swift 4.x

class TapGestureRecognizer: UITapGestureRecognizer {
    var highlightOnTouch = true

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)

        if highlightOnTouch {
            let bgcolor = view?.backgroundColor
            UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
                self.view?.backgroundColor = .lightGray
            }) { (_) in
                UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
                    self.view?.backgroundColor = bgcolor
                })
            }
        }
    }

}
缱倦旧时光 2024-12-31 23:50:10

斯威夫特 5.7

import UIKit

final class HighlightingTapRecognizer: UITapGestureRecognizer {
    private(set) var viewToHighlight: UIView
    
    init(target: Any?, action: Selector?, viewToHighlight: UIView) {
        self.viewToHighlight = viewToHighlight
        super.init(target: target, action: action)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        
        UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
            self.viewToHighlight.alpha = 0.7
        })
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesEnded(touches, with: event)
        
        UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
            self.viewToHighlight.alpha = 1
        })
    }
}

Swift 5.7

import UIKit

final class HighlightingTapRecognizer: UITapGestureRecognizer {
    private(set) var viewToHighlight: UIView
    
    init(target: Any?, action: Selector?, viewToHighlight: UIView) {
        self.viewToHighlight = viewToHighlight
        super.init(target: target, action: action)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        
        UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
            self.viewToHighlight.alpha = 0.7
        })
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesEnded(touches, with: event)
        
        UIView.animate(withDuration: 0.1, delay: 0, options: [.allowUserInteraction, .curveLinear], animations: {
            self.viewToHighlight.alpha = 1
        })
    }
}
小ぇ时光︴ 2024-12-31 23:50:10

Swift 4 及以上版本

final class HighlightingTapRecognizer: UITapGestureRecognizer {
    private(set) var viewToHighlight: UIView

    init(target: Any?, action: Selector?, viewToHighlight: UIView) {
        self.viewToHighlight = viewToHighlight
        super.init(target: target, action: action)
    }


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesEnded(touches, with: event)

        let xPosition = touches.first?.location(in: viewToHighlight).x
        let yPosition = touches.first?.location(in: viewToHighlight).y

        let width = 30
        let height = 30

        let view11 = UIView(frame: CGRect(x: Int(xPosition!), y: Int(yPosition!), width: width,     height: height))
        view11.isHidden = true
        view11.backgroundColor = .darkGray.withAlphaComponent(0.5)
        view11.layer.cornerRadius = view11.frame.height / 2
        view11.layer.masksToBounds = true

        self.viewToHighlight.addSubview(view11)

        view11.isHidden = false
        Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { _ in
            view11.removeFromSuperview()
        })

    }
}

使用:

let tap = HighlightingTapRecognizer(target: self, action: #selector(self.YourActionFunc(_:)), viewToHighlight: previewView)
previewView.addGestureRecognizer(tap)

Swift 4 and above

final class HighlightingTapRecognizer: UITapGestureRecognizer {
    private(set) var viewToHighlight: UIView

    init(target: Any?, action: Selector?, viewToHighlight: UIView) {
        self.viewToHighlight = viewToHighlight
        super.init(target: target, action: action)
    }


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesEnded(touches, with: event)

        let xPosition = touches.first?.location(in: viewToHighlight).x
        let yPosition = touches.first?.location(in: viewToHighlight).y

        let width = 30
        let height = 30

        let view11 = UIView(frame: CGRect(x: Int(xPosition!), y: Int(yPosition!), width: width,     height: height))
        view11.isHidden = true
        view11.backgroundColor = .darkGray.withAlphaComponent(0.5)
        view11.layer.cornerRadius = view11.frame.height / 2
        view11.layer.masksToBounds = true

        self.viewToHighlight.addSubview(view11)

        view11.isHidden = false
        Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { _ in
            view11.removeFromSuperview()
        })

    }
}

use:

let tap = HighlightingTapRecognizer(target: self, action: #selector(self.YourActionFunc(_:)), viewToHighlight: previewView)
previewView.addGestureRecognizer(tap)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文