UITextfield不能作为iOS 7中UISearchBar的子视图?

时间:2013-09-24 23:27:09

标签: ios uitextfield uinavigationbar ios7 uisearchbar

此代码在iOS 6中运行良好,但在iOS 7中,文本字段在navigationBar中是灰色的,而不是可点击的?看看这张图片中的区别

enter image description here

可能有什么问题?我不知道他们在iOS 7中究竟有什么变化,也不知道从哪里开始寻找解决这个问题...

/问候

UITextField *sbTextField = (UITextField *)[searchBar.subviews lastObject];
[sbTextField removeFromSuperview];

CGRect rect = searchBar.frame;
rect.size.height = 32;
rect.size.width = 210;
sbTextField.frame = rect;
 // [sbTextField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation]; Not working in iOS7
 // [sbTextField setPlaceholder:NSLocalizedString(@"HintSearchExercise", nil)]; Not working in iOS 7

[sbTextField setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
[searchBar removeFromSuperview];

UIBarButtonItem *searchBarNavigationItem = [[UIBarButtonItem alloc] initWithCustomView:sbTextField];

[[self navigationItem] setLeftBarButtonItem:searchBarNavigationItem];

1 个答案:

答案 0 :(得分:3)

ios7 [searchBar.subviews lastObject]中的

文本字段,而是一个UIView实例,作为控件周围的附加容器。

cocktailicious存在同样的问题,我打算在UISearchBar上使用以下类别:

@interface UISearchBar (Workarounds)
@property (readonly, nonatomic) UITextField *textField;
@end

@implementation UISearchBar (Workarounds)
- (UITextField *)textField
{
    for (UIView *view in [self subcontrols]) {
        if ([view isKindOfClass:[UITextField class]]) {
            return (UITextField *)view;
        }
    }
    return nil;
}

- (NSArray *)subcontrols
{
    return self.subviews.count == 1 ? [self.subviews.firstObject subviews] : self.subviews;
}
@end

- subcontrols方法可以解决问题。