在ABPeoplePickerNavigationController中更改UISearchBar的tintColor

时间:2010-09-01 14:13:58

标签: iphone objective-c uiviewcontroller uisearchbar tintcolor

我想在下面的ABPeoplePickerNavigationController中自定义颜色是我的完整代码:

ABPeoplePickerNavigationController *objPeoplePicker = [[ABPeoplePickerNavigationController alloc] init];
[objPeoplePicker setPeoplePickerDelegate:self];
objPeoplePicker.topViewController.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.294 green:0.278 blue:0.247 alpha:1.0];
objPeoplePicker.topViewController.searchDisplayController.searchBar.tintColor = [UIColor colorWithRed:0.294 green:0.278 blue:0.247 alpha:1.0];
[self presentModalViewController:objPeoplePicker animated:YES];

自定义NavigationBar tintColor,此行有效:

objPeoplePicker.topViewController.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.294 green:0.278 blue:0.247 alpha:1.0];

但是,我还想自定义searchBar的tintColor:

objPeoplePicker.topViewController.searchDisplayController.searchBar.tintColor = [UIColor colorWithRed:0.294 green:0.278 blue:0.247 alpha:1.0];

该行不起作用。我想我可能会引用错误的searchBar ....你能指出我正确的方向吗?

4 个答案:

答案 0 :(得分:3)

我遇到了同样的问题。更改navBar颜色很容易。然而,更改UISearchBar颜色并非如此。首先我做的是检查

if( picker.searchDisplayController == nil ) 
  NSLog(@"searchDisplayController is nil");
if( picker.topViewController.searchDisplayController == nil ) 
  NSLog(@"topViewController.searchDisplayController is nil");

两次searchDisplayController都是零。我最终做的是遍历视图层次结构以查找UISearchBar视图。肯定有一个是正确的。所以这是我的最终代码。如果有人有更好的解决方案,我很乐意听到。

static BOOL foundSearchBar = NO;
- (void)findSearchBar:(UIView*)parent mark:(NSString*)mark {

  for( UIView* v in [parent subviews] ) {

    if( foundSearchBar ) return;

    NSLog(@"%@%@",mark,NSStringFromClass([v class]));

    if( [v isKindOfClass:[UISearchBar class]] ) {
      [(UISearchBar*)v  setTintColor:[UIColor blackColor]];
      foundSearchBar = YES;
      break;
    }
    [self findSearchBar:v mark:[mark stringByAppendingString:@"> "]];
  }
}

- (void)pickPerson:(BOOL)animated {
  foundSearchBar = NO;
  ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
  [[picker navigationBar] setTintColor:[UIColor blackColor]];

  picker.peoplePickerDelegate = self;
  picker.displayedProperties = [NSArray arrayWithObjects:
                  [NSNumber numberWithInt:kABPersonEmailProperty],
                  nil];

  [self presentModalViewController:picker animated:animated];
  [picker release];

  [self findSearchBar:[picker view] mark:@"> "];
}

答案 1 :(得分:1)

我没有改变颜色,而是将图像添加到背景中:

[mysearchBar setBackgroundImage:[UIImage imageNamed:@"<#Your image name#>"]];

答案 2 :(得分:1)

您现在可以使用UISearchBar外观代理执行此操作:

UISearchBar* addressBookSearchBar = [UISearchBar appearanceWhenContainedIn:[ABPeoplePickerNavigationController class], nil];
addressBookSearchBar.tintColor = [UIColor blackColor];

答案 3 :(得分:1)

对于iOS7 +,最简单的方法是操纵UISearchBar的外观代理:

[[UISearchBar appearance] setBarTintColor:[UIColor blackColor]];