自定义搜索结果按钮在UISearchBar中具有奇怪的行为

时间:2011-07-02 12:09:41

标签: iphone objective-c xcode uisearchbar

我将UISearchBar子类化,以便按照以下方式(.m文件)将自定义图像设置为搜索结果按钮:

#import "CustomUISearchBar.h"

#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

@implementation GipUISearchBar

- (void)layoutSubviews 
{    
    UITextField *searchField = nil;    
UIView *backGround = nil;
UIButton *cancelButton = nil;
NSUInteger numViews = [self.subviews count];    
for(int i = 0; i < numViews; i++) 
{       
    if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) 
    {           
        searchField = [self.subviews objectAtIndex:i];       
    }
    else if ([[self.subviews objectAtIndex:i] isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
    {       
        backGround = [self.subviews objectAtIndex:i];  
    }       
    else if ([[self.subviews objectAtIndex:i] isKindOfClass:[UIButton class]]) 
    {       
        cancelButton = [self.subviews objectAtIndex:i];                     [cancelButton setTintColor:RGB(22.0,38.0,111.0)];

    }
}    

if(!(searchField == nil)) 
{        
    searchField.layer.cornerRadius=15.0f;
    searchField.layer.masksToBounds=YES;
    searchField.layer.borderColor = [RGB(26.0,141.0,223.0)CGColor];
    searchField.layer.borderWidth = 2.0f;       

    UIImage *glassImage = [UIImage imageNamed: @"search_icon.png"];    
    UIImageView *iView = [[UIImageView alloc] initWithImage:glassImage];    
    searchField.leftView = iView;    
    [iView release];

    UIImage *historyImage = [UIImage imageNamed:@"history_button.png"];
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [historyButton setBackgroundImage:historyImage forState:UIControlStateNormal];
    [historyButton setBackgroundImage:historyImage forState:UIControlStateSelected];
    [historyButton setBackgroundImage:historyImage forState:UIControlStateDisabled];
    [historyButton setBackgroundImage:historyImage forState:UIControlStateHighlighted];

    historyButton.frame = CGRectMake(0, 
                                     0, 
                                     historyImage.size.width-3, 
                                     historyImage.size.height-3);
    historyButton.layer.borderColor = [RGBA(0.0,0.0,0.0,0.0)CGColor];
    historyButton.layer.borderWidth = 0.0f;

    searchField.rightView = historyButton;
}

if (!(backGround == nil))
    [backGround removeFromSuperview];



[super layoutSubviews]; 
}

问题是当我触摸搜索栏内部并调整大小时,我看到此按钮从左向右移动。如何禁用此行为?

1 个答案:

答案 0 :(得分:0)

尝试评论以下几行。

[super layoutSubviews];

因为您似乎通过继承它来覆盖UISearchBar的布局。