在iPhone应用程序开发中自定义搜索栏

时间:2011-12-28 10:56:27

标签: iphone ios uisearchbar uisearchdisplaycontroller uisearchbardelegate

在我的应用程序中,我必须在tableview的头部添加一个搜索栏。我能够添加搜索栏但问题是没有添加ios的默认搜索栏我可以添加自定义搜索栏吗?我正在给出一张图片,看看会有哪些类型的搜索栏...

enter image description here

5 个答案:

答案 0 :(得分:9)

您可以继承UISearchBar并覆盖layoutSubviews方法:

- (void)layoutSubviews {
   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.textColor = [UIColor whiteColor];
       [searchField setBackground: [UIImage imageNamed:@"yourImage.png"] ];
       [searchField setBorderStyle:UITextBorderStyleNone];
   }

   [super layoutSubviews];
}

你也可以:

//to clear searchbar backgraound
- (void) clearSearchBarBg
{
    for (UIView *subview in theSearchBar.subviews) 
    {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
        {
            [subview removeFromSuperview];
            break;
        }
    }
}

//display showSearchButtonInitially in a keyboard 
- (void)showSearchButtonInitially
{
    UIView * subview;
    NSArray * subviews = [theSearchBar subviews];

    for(subview in subviews)
    {
        if( [subview isKindOfClass:[UITextField class]] )
        {
            NSLog(@"setEnablesReturnKeyAutomatically");
            [((UITextField*)subview) setEnablesReturnKeyAutomatically:NO];
            ((UITextField*)subview).delegate=self;
            [((UITextField*)subview) setEnabled:TRUE];
            ((UITextField*)subview).borderStyle = UITextBorderStyleNone;
            break;
        }
    }
}

答案 1 :(得分:3)

查找UISearchBar的Apple DOC

enter image description here

你有很多方法可以得到你想要的任何东西

您可以通过

在搜索栏内获取UITextView
UITextField *textField = [searchBar.subviews objectAtIndex:2];

if ([textField isKindOfClass:[UITextField class]]) {
    //Do your customization
}

再次为UITextField查找AppleDoc。你也有很多方法。

答案 2 :(得分:0)

是的,绝对是。您可以创建自定义搜索栏(这是UIView的子类),并将其作为子视图添加到tableHeaderView

答案 3 :(得分:0)

[[searchBarDesign.subviews objectAtIndex:0] removeFromSuperview];

答案 4 :(得分:0)

我认为最好只在加载时设置UISearchBar的所有属性。

@interface MySearchBar : UISearchBar

@end


@implementation MySearchBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self myInitialize];
    }
    return self;
}

-(void)awakeFromNib

{
    [super awakeFromNib];
    [self myInitialize];
}

-(void)myInitialize
{
    self.backgroundImage = [UIImage imageNamed:@"image.png"];

    for (UIView* subview in self.subviews) {
        if ([subview isKindOfClass:[UITextField class]]) {
            //customize text field
            UITextField* textfield = (UITextField*) subview;
        }
    }
}

@end