【问题标题】:How to create a universal custom UINavigationBar back button without skewing the image如何在不倾斜图像的情况下创建通用自定义 UINavigationBar 后退按钮
【发布时间】:2017-06-18 12:13:30
【问题描述】:

所以我尝试为每次后退箭头出现在 UINavigationController 中设置一个通用后退按钮图像。但是,每次我尝试实现时,图像都会倾斜和扩展。原始图像是一个简单的后退箭头。但是,后退按钮图像(可以普遍使用)正在倾斜,如下所示:

我已经尝试在我的 AppDelegate 中使用以下代码 - 仍然没有成功。

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Attempt 1
    [[UIBarButtonItem appearance]
     setBackButtonBackgroundImage:[UIImage imageNamed:@"Back"]
     forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    // Attempt 2
    UIImageView *buttonBack = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    buttonBack.image = [UIImage imageNamed:@"Back"];
    [[UIBarButtonItem appearance]
     setBackButtonBackgroundImage:buttonBack.image
     forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}

【问题讨论】:

    标签: ios objective-c uinavigationcontroller uinavigationbar uibarbuttonitem


    【解决方案1】:

    你需要设置你的后退按钮的 UIImageView 的 contentMode。

    使用此代码设置图像以适应 UIImageView 的框架并保持图像的纵横比:

    // Attempt 2
    UIImageView *buttonBack = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    buttonBack.image = [UIImage imageNamed:@"Back"];
    // this line sets the aspect mode
    buttonBack.contentMode = UIViewContentModeScaleAspectFit;
    [[UIBarButtonItem appearance]
     setBackButtonBackgroundImage:buttonBack.image
     forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    

    【讨论】:

    • 不幸的是,您的解决方案仍然遇到同样的问题。甚至尝试设置正确的 CGRectMake:initWithFrame:CGRectMake(0, 0, 16, 16)](16 x 16 是图标大小)。仍然像原始屏幕截图中那样显示。
    • 您是否尝试过将 UIImageView 设置为 UIBarButtonItem 的 customView 而不是 backgroundImage?
    • 我尝试使用以下代码,但遇到了崩溃错误:1. UIView *backButtonView; 2. backButtonView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Back"]]; 3. [[UIBarButtonItem appearance] setCustomView:backButtonView];(数字代表数字线)
    【解决方案2】:

    答案比预期的要简单得多。删除一些额外的代码并将其修剪到它的准系统 - 你会得到这样的东西(在 AppDelegate 中,didFinishLaunchingWithOptions):

    // Custom Back Button
    UIImageView *buttonBack = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
    buttonBack.image = [UIImage imageNamed:@"Back"];
    buttonBack.contentMode = UIViewContentModeScaleAspectFit;
    

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 1970-01-01
      • 2011-04-29
      • 2012-06-16
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      相关资源
      最近更新 更多