【问题标题】:How to set custom UINavigationBarButton color如何设置自定义导航栏按钮颜色
【发布时间】:2011-11-22 01:03:40
【问题描述】:

我正在尝试为我的 UINavigationBar 上的按钮设置自定义颜色,但仅当其中显示特定的 UIViewController 时(我知道这是可疑的 UI 设计,但这是特定的客户要求)。

我们当前的实现使用 Swizzle 来覆盖所有 UINavigationBar 对象的 drawRect。这是必要的,因此我们的自定义导航栏颜色将应用于标准 iOS 屏幕(例如通过标准 API 添加新联系人时)。

我想将一个特定 UIViewController 的导航栏色调更改为与其他不同,但 Swizzle 始终优先。

我正在 iOS 4.3 模拟器中进行测试。我们支持 iOS 3.x 及更高版本的客户端(iPhone、iPod 和 iPad),所以我不能只使用更新的 iOS 5 API 来自定义它。

我尝试过的其他事情,但没有成功:

  • 添加setStyle 调用(根据this workaround)以使按钮再次更新。

  • 我尝试了我发现的UINavigationButton hack here(我知道这是一个私有 API,并且有可能被 Apple 拒绝该应用程序)。我也尝试将该代码放入viewWillAppear

【问题讨论】:

    标签: objective-c cocoa-touch iphone-sdk-3.0


    【解决方案1】:

    我认为this question 的答案会回答你的。我的答案使用 UISegmentedControl,不需要任何私有 API 调用。

    【讨论】:

    • 仅供参考,我更新了问题,因为我发现问题的根源是我们代码中其他地方正在执行的 Swizzle。使用 UISegmentedControl 可能仍然是一个合适的解决方法,所以我会看看它。
    • 如果可能的话,您不应该在运输应用中使用 swizzling。
    • 我同意,但遗憾的是这是我必须支持的现有代码:-(
    【解决方案2】:

    根据this Stackoverflow answer,我通过创建一个带有自定义背景图像的 UIButton 来实现这一点。

    如果它对任何人有帮助,这是我的代码:

    #import <QuartzCore/QuartzCore.h>
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"mybackground.png"] forState:UIControlStateNormal];
    [button setTitle:NSLocalizedString(@"Login", @"Button (9 chars limit) - Login") forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f];
    [button.layer setCornerRadius:5.0f];
    [button.layer setMasksToBounds:YES];
    [button.layer setBorderWidth:1.0f];
    [button.layer setBorderColor: [[UIColor grayColor] CGColor]];
    button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0);
    [button addTarget:self action:@selector(myLoginActionMethod:) forControlEvents:UIControlEventTouchUpInside];
    
    self._loginButton= [[UIBarButtonItem alloc] initWithCustomView:button]; 
    

    一般来说,我认为最好像这样在 UIViewController 中设置色调(尽管在我的情况下这不起作用,因为 drawRect swizzle 在我的代码中的 UINavigationBar 上就位):

    self.navigationController.navigationBar.tintColor=[UIColor blueColor];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多