簡體   English   中英

IOS 7 無法更改搜索欄的背景圖片

[英]IOS 7 Unable to change background image of search bar

我無法在我的 IOS 7 中自定義搜索欄。

我正在使用以下代碼更改 IOS6 中的搜索欄背景

for (UIView * v in sarchBar.subviews)
{
    if ([v isKindOfClass:NSClassFromString(@"UISearchBarTextField")])
    {
        v.superview.alpha = 0;
        UIView *containerView = [[UIView alloc] initWithFrame:sarchBar.frame];
        [containerView addSubview:v];
        [self.view addSubview:containerView];
        [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]];
        [[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    }
}

其次,如果我自定義搜索控制器以刪除搜索欄中的默認取消按鈕,則它在 IOS6 中工作正常,但使用自定義搜索控制器,它不會在 IOS7 中搜索。

如果您改用文本字段並更改背景圖像會更好,因為它是子類並繼承了相同的屬性。

編輯:我可能誤讀了原始問題.. 下面的答案向您展示了如何從UISearchBar安全地獲取UITextField

回顧您的代碼,看起來您好像在嘗試直接修改UISearchBar的視圖層次結構。 我知道蘋果打擊了在 iOS 7 中的其他 UI 元素(如UIAlertView )上做這樣的事情,但我不確定他們是否對UISearchBar做了同樣的事情。

關於取消按鈕..你不能只使用UISearchBar上的showsCancelButton屬性嗎?


我編寫了以下類別來嘗試從UISearchBar獲取UITextField

它適用於 iOS 7 但未在 6 上測試(我不明白為什么它不會)

UISearchBar+BSSearchBar.h

//
// Created by Liam Nichols on 07/04/2014.
// Copyright (c) 2014 Liam Nichols. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface UISearchBar (BSSearchBar)

- (void)setTextColor:(UIColor *)color;

- (UITextField *)internalTextField;

@end

UISearchBar+BSSearchBar.m

//
// Created by Liam Nichols on 07/04/2014.
// Copyright (c) 2014 Liam Nichols. All rights reserved.
//

#import "UISearchBar+BSSearchBar.h"


@implementation UISearchBar (BSSearchBar)

- (void)setTextColor:(UIColor *)color
{
    UITextField *textField = [self internalTextField];
    textField.textColor = color;
}

- (UITextField *)internalTextField
{
    return [UISearchBar findTextFieldInView:self];
}

+ (UITextField *)findTextFieldInView:(UIView *)view
{
    for (id subview in view.subviews)
    {
        if ([subview isKindOfClass:[UITextField class]])
        {
            return subview;
        }

        UITextField *subviewTextField = [UISearchBar findTextFieldInView:subview];
        if ([subviewTextField isKindOfClass:[UITextField class]])
        {
            return subviewTextField;
        }
    }
    return nil;
}

@end

希望能幫助到你

試試這個背景圖片..我希望它有幫助

 for(UIView *subView in [searchBarObj subviews]) {
    for(UIView *subSubView in [subView subviews]) {
        if([subSubView conformsToProtocol:@protocol(UITextInputTraits)]) {
            [(UITextField *)subSubView setBackgroundColor: [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]]];
        }
    }
  }  

謝謝 ..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM