1

UISearchBar の [キャンセル] ボタンの背景を変更する次のコードがあります。

for( UIView *subview in self.searchBar.subviews ){
    if ([subview isKindOfClass:[UIButton class]]) {
        [(UIButton *)subview setEnabled:YES];
        [(UIButton *)subview setTitle:@"New Button Text" forState:UIControlStateNormal];
        ((UIButton *)subview).tintColor = [UIColor colorWithRed:4/255.0 green:119/255.0 blue:152/255.0 alpha:1.0];
    }
}

問題は、このコードが iOS7 で動作しないことです! UISearchBar のビューの構造で何が変更されましたか?

編集:ここでテストされ、これは UISearchBar の新しい階層です:

UISearchBar:
---UIView:
------UISearchBarBackground
------UISearchBarTextField
------UINavigationButton

問題は、テストできないことif ([sub isKindOfClass:[UINavigationButton class]])です。この行はコンパイル エラーをスローします。Use of undeclared identifier: UINavigationButton

4

3 に答える 3

1

解決策: 独自のボタンを作成しました。このようにして、Apple が要素に対して何をしたかを知る必要なく、すべてのプロパティを管理できます。

UIView auxsearchBar と新しい Button を含むを作成するだけです。

self.searchBar.showsCancelButton = NO; //don`t show the original cancelButton

self.cancelSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.cancelSearchButton.frame = CGRectMake(250, 6, 60, 31);
[self.cancelSearchButton setTitle:@"Cancelar" forState:UIControlStateNormal];
[self.cancelSearchButton addTarget:self action:@selector(searchBarCancelButtonClicked) forControlEvents:UIControlEventTouchUpInside];
NSString *fontName = [[self.cancelSearchButton titleLabel] font].fontName;
[[self.cancelSearchButton titleLabel] setFont:[UIFont fontWithName:fontName size:11.0]];
UIView *aux = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
aux.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
aux.layer.borderWidth = 1.0f;
aux.layer.borderColor = [UIColor lightGrayColor].CGColor;
aux.layer.cornerRadius = 0.0f;
[aux addSubview:self.searchBar];
[aux addSubview:self.cancelSearchButton];

- (void)searchBarCancelButtonClicked{
    //do whatever I want to do here
}
于 2013-10-18T15:32:07.580 に答える
0

これを実現するには、iOS ランタイム プロパティ_cancelButtonを利用できます。

UIButton *cancelButton = [self.searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitleColor:[UIColor yourColor] forState:UIControlStateNormal];

テキストを変更するには

[self.searchBar setValue:@"customString" forKey:@"_cancelButtonText"];
于 2015-11-26T10:38:34.953 に答える