【问题标题】:Is there an easy way to change the text color of a UIBarButtonItem without using an image?有没有一种简单的方法可以在不使用图像的情况下更改 UIBarButtonItem 的文本颜色?
【发布时间】:2011-04-13 16:01:36
【问题描述】:

有没有一种简单的方法可以在不使用 UIImage 作为背景的情况下更改 UIBarButtonItem 的文本颜色?

默认情况下,文本始终为白色。我想让它变黑。

【问题讨论】:

    标签: iphone cocoa-touch ios4 uibarbuttonitem


    【解决方案1】:

    感谢IOS 5.0,您不需要为此使用图像。您可以使用以下代码设置各种文本属性。

    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Title"     style:UIBarButtonItemStyleBordered target:nil action:nil];
    
    if ([button respondsToSelector:@selector(setTitleTextAttributes:forState:)]) {
    
        NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                   kTextColor,UITextAttributeTextColor,
                                                   nil];
    
        [[UIBarButtonItem appearance] setTitleTextAttributes:textAttributes                   
                                      forState:UIControlStateNormal];
    
    }
    

    【讨论】:

      【解决方案2】:

      我宁愿在 UIBarButtonItem 中使用 UIButton 并自定义它。

      这是一个自定义 UIButton 的自定义图形示例。这个想法保持不变,使用 UIBarButtonItem 的 initWithCustomView 将其他易于定制的东西放入其中。

      self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
      [closeButton setImage:[UIImage imageNamed:@"webview_close_button_normal.png"] forState:UIControlStateNormal];
      [closeButton setImage:[UIImage imageNamed:@"webview_close_button_pressed.png"] forState:UIControlStateHighlighted];
      closeButton.frame = CGRectMake(0, 0, 121, 36);
      [closeButton addTarget:self action:@selector(closeAdViewController) forControlEvents:UIControlEventTouchUpInside];
      
      UIBarButtonItem * aBarButtonAdClose = [[[UIBarButtonItem alloc] initWithCustomView:closeButton] autorelease];
      

      【讨论】:

        【解决方案3】:

        您可以使用

        设置自定义视图

        [[UIBarButtonItem alloc] - (id)initWithCustomView:(UIView *)customView]

        【讨论】:

          【解决方案4】:

          您的问题的直接答案是否定的。

          您不能简单地通过设置UIBarButtonItem 的属性之一来更改其颜色。您可以设置包含UIBarButtonItems 的UIToolBarUINavigationBartintColor 属性,但这也会影响工具栏本身的颜色,并且不会提供太多自定义。

          如果这对您不起作用,其他答案建议的自定义视图是一个好主意。

          祝你好运!

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          • 2019-03-19
          相关资源
          最近更新 更多