[英]Highlighting a UIView similar to UIButton
我有一個帶有多個子視圖的 UIView 和一個識別出關聯的 Tap 手勢,我想模仿它具有“觸摸”效果。 也就是說,當點擊發生時,我想顯示容器視圖具有不同的背景顏色,並且任何子視圖 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
}];
}
setHighlighted 不是動畫視圖屬性。 另外,您說的是兩件相反的事情:您同時將Highlighted 設置為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;
});
}
標簽必須具有不同的textColor
與它的highlightedTextColor
以便發生可見的事情。
斯威夫特 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
值,因此它看起來像一個亮點。
簡單的解決方案是覆蓋點擊手勢識別器,如下所示:
斯威夫特 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
})
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.