在iOS8中使用UISearchBar启用取消按钮

时间:2014-11-19 15:20:31

标签: iphone cocoa-touch ios8 uisearchbar

是否有任何方法可以启用UISearchBar的“取消”按钮?现在每当我调用resignFirst响应器时,取消按钮都会被禁用。只有当我再次点按搜索栏时,才会启用取消。反正有没有停止取消按钮?

3 个答案:

答案 0 :(得分:7)

这是适用于iOS 8和Swift的工作解决方案。

func enableCancleButton (searchBar : UISearchBar) {
    for view1 in searchBar.subviews {
        for view2 in view1.subviews {
            if view2.isKindOfClass(UIButton) {
                var button = view2 as! UIButton
                button.enabled = true
                button.userInteractionEnabled = true
            }
        }
    }
}

答案 1 :(得分:4)

对于iOS7:

- (void)enableCancelButton{
    for (UIView *view in self.subviews){
        for (id subview in view.subviews){
            if ([subview isKindOfClass:[UIButton class]]){
                [subview setEnabled:YES];
                return;
            }
        }
    }
}

要使上述代码在iOS 8中有效, 您需要在启用子视图之前添加延迟:

- (void)enableCancelButton{
    for (UIView *view in self.subviews){
        for (id subview in view.subviews){
            if ([subview isKindOfClass:[UIButton class]]){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10), dispatch_get_main_queue(), ^{
                    [subview setEnabled:YES];
                });
                return;
            }
        }
    }
}

答案 2 :(得分:0)

UIBarButtonItem.appearance().enabled = true 

为我做了伎俩