我有一个UISearchBar,如下所示。如何更改“取消”按钮的文本颜色?

最佳答案

这个问题是在不久前被问到的,因此我认为被问到的人已经找到了解决方案。但是以防万一其他碰巧碰到同样的问题。这是我的解决方案。

我有一个带有取消按钮的UISearchBar,仅当点按UISearchBar的文本字段时才会显示。因此,在UISearchBar的子类中覆盖-(void)layoutSubviews的解决方案不是我的选择。无论如何,我使用公共(public)方法来设置UISearchBar(CustomSearchBar)的子类,以设置取消按钮的字体和textColor。创建UISearchBar时,请确保将搜索栏的文本字段委托(delegate)设置为self,并且创建搜索栏的类将实现UITextFieldDelegate协议(protocol)。当用户点击搜索栏的文本字段时,将通知其委托(delegate)并调用CustomSearchBar的方法。之所以在此进行操作,是因为这是出现“取消”按钮的时刻,因此我知道它位于 View 层次结构中,因此我可以对其进行自定义。

这是代码:

用于在MyRootViewController中创建UISearchBar

CustomSearchBar *searchBar = [[CustomSearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 40)];
[searchBar setBarStyle:UIBarStyleDefault];
[searchBar setTintColor:[UIColor whiteColor]];

for (UIView *view in [searchBar subviews])
{
    if ([view isKindOfClass:[UITextField class]])
    {
        UITextField *searchTextField = (UITextField *)view;
        [searchTextField setDelegate:self];
    }
}

self.searchBar = searchBar;
[searchBar release];

MyRootViewController中的UITextFieldDelegate(确保它实现了UITextFieldDelegate协议(protocol))
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.searchBar setCloseButtonFont:[UIFont fontWithName:@"American Typewriter" size:14] textColor:[UIColor grayColor]];
}

这是UISearchBar子类中的public方法
- (void)setCloseButtonFont:(UIFont *)font textColor:(UIColor *)textColor
{
    UIButton *cancelButton = nil;

    for(UIView *subView in self.subviews)
    {
        if([subView isKindOfClass:[UIButton class]])
        {
            cancelButton = (UIButton*)subView;
        }
    }

    if (cancelButton)
    {
        /* For some strange reason, this code changes the font but not the text color. I assume some other internal customizations      make this not possible:

        UILabel *titleLabel = [cancelButton titleLabel];
        [titleLabel setFont:font];
        [titleLabel setTextColor:[UIColor redColor]];*/

        // Therefore I had to create view with a label on top:
        UIView *overlay = [[UIView alloc] initWithFrame:CGRectMake(2, 2, kCancelButtonWidth, kCancelButtonLabelHeight)];
        [overlay setBackgroundColor:[UIColor whiteColor]];
        [overlay setUserInteractionEnabled:NO]; // This is important for the cancel button to work
        [cancelButton addSubview:overlay];

        UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, kCancelButtonWidth, kCancelButtonLabelHeight)];
        [newLabel setFont:font];
        [newLabel setTextColor:textColor];
        // Text "Cancel" should be localized for other languages
        [newLabel setText:@"Cancel"];
        [newLabel setTextAlignment:UITextAlignmentCenter];
        // This is important for the cancel button to work
        [newLabel setUserInteractionEnabled:NO];
        [overlay addSubview:newLabel];
        [newLabel release];
        [overlay release];
    }
}

关于iphone - 如何更改UISearchbar取消按钮的文本颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6992917/

10-13 03:50