点击'X'元素时触发UISearchBar和事件 [英] UISearchBar and event fired when 'X' element is tapped
问题描述
在UISearchBar上,有一个X元素,允许您一次清除所有内容。有没有办法在发生这种情况时收到通知?
On the UISearchBar, there's an X element that allows you to clear all of the contents at once. Is there a way to get notified when this happens?
UISearchBarDelegate :: searchBarCancelButtonClicked
仅在取消时触发按钮被点击。
UISearchBarDelegate::searchBarCancelButtonClicked
is fired only when the "Cancel" button is tapped.
推荐答案
UISearchBar
没有委托此事件的方法。通过实现回调委托的 textDidChange:
方法并检查空字符串,你几乎可以得到你想要的东西。
The UISearchBar
doesn't have a delegate method for this event. You can nearly get what you want by implementing the textDidChange:
method of the callback delegate and checking for an empty string.
我不推荐它,但还有另一种可能的方法。 UISearchBar
由UITextField组成,它有一个委托方法,当用户点击清除按钮时会调用该方法( textFieldShouldClear:
)。您可以通过遍历 UISearchBar
的子视图来获取 UITextField
:
I don't recommend it, but there is another possible way. The UISearchBar
is composed of a UITextField, which does have a delegate method that is called when the user taps the clear button (textFieldShouldClear:
). You can get the UITextField
by traversing the UISearchBar
's child views:
(这是在派生的 UISearchBar
类的上下文中)
(this is in the context of a derived UISearchBar
class)
- (UIView*) textField
{
for (UIView* v in self.subviews)
{
if ( [v isKindOfClass: [UITextField class]] )
return v;
}
return nil;
}
从这里,你可以重新分配 UITextField
委托您自己的实现,注意将委托调用转发给旧委托。这样你就可以拦截 textFieldShouldClear:
。或者,如果结果 UISearchBar
是 UITextField
的委托,它包含你可以调用textFieldShouldClear:。 ..不理想,但技术上可行。
from here, you could re-assign the UITextField
delegate to your own implementation, taking care to forward delegate calls to the old delegate. This way you could intercept textFieldShouldClear:
. Or if it turns out the UISearchBar
is the delegate for the UITextField
it contains you could swizzle the call to textFieldShouldClear:... Not ideal, clearly, but technically feasible.
这篇关于点击'X'元素时触发UISearchBar和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!