【问题标题】:remove the border of uitextfield in uisearchbar移除uisearchbar中uitextfield的边框
【发布时间】:2012-05-23 00:05:58
【问题描述】:

我想将 UISearchBar 控件自定义为如下图所示的样式:

首先我应该删除背景视图,然后在 UISearchBar 中找到 UITextfiled,扩展 UITextfiled 的框架并删除它的边框。

这是我的代码:

UITextField *searchField;

NSUInteger numViews = [self.subviews count];
for(int i = 0; i != numViews; i++) {
    if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
        searchField = [self.subviews objectAtIndex:i];
    }
}
if(!(searchField == nil)) {

    [searchField setBorderStyle:UITextBorderStyleNone];
    searchField.frame = self.frame; //modify the frame
}

[[self.subviews objectAtIndex:0]removeFromSuperview]; //remove the background.

结果是 UITextField 的边界还在。 :(

我的问题是: 1.为什么我不能修改UISearchBar的UITextField的外观?

2.如何去除UISearchBar中UITextfield的边框。

非常感谢!

【问题讨论】:

    标签: ios cocoa-touch uitextfield uisearchbar


    【解决方案1】:

    子类 UISearchBar 并覆盖 layoutSubViews 以删除搜索栏背景和文本字段边框子视图:

    - (void)layoutSubviews
    {    
        [super layoutSubviews];
    
        for (UIView *subview in self.subviews) {
            // Remove the default background
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
                [subview removeFromSuperview];
            }
    
            // Remove the rounded corners
            if ([subview isKindOfClass:NSClassFromString(@"UITextField")]) {
                UITextField *textField = (UITextField *)subview;
                for (UIView *subsubview in textField.subviews) {
                   if ([subsubview isKindOfClass:NSClassFromString(@"UITextFieldBorderView")]) {
                        [subsubview removeFromSuperview];
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 或者如果你不想子类化,把它放在你/lazy/加载你的UISearchBar的地方:dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){/ *这里的魔法*/ });
    【解决方案2】:

    我不确定这一点,但是我怀疑您能够像您的图像中那样实现UISearchBar 的唯一方法是创建UISearchBar 的新子类。使用它,您可以将其设置为与图片中的完全一样。

    如果您决定走子类化路线,This post 可能会对您有所帮助。

    【讨论】:

    • 子类方式行不通。还是谢谢大家,我想我得自己创建一个SearchBar,不知道是不是好办法。我仍然不明白为什么我不能根据需要修改 UITextField 的外观。无论如何,还是谢谢你。
    • biaobiaoqi,你有没有找到办法做到这一点?我需要自己做这样的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    相关资源
    最近更新 更多