【问题标题】:Centering image with Title Label in Navigation Bar在导航栏中使用标题标签居中图像
【发布时间】:2016-11-10 11:01:15
【问题描述】:

我正在向导航栏添加自定义标题标签和自定义图像。我可以在我想要的位置正确添加标题标签,但我无法将图像水平居中到该标签。我正在添加一个屏幕截图和我使用的可以提供帮助的代码。

-(void)addIconInNavBar
{
    CGSize imageSize = CGSizeMake(lblHeight, lblHeight);
    CGFloat marginX = (self.navigationController.navigationBar.frame.size.width) - (imageSize.width / 2);
    CGFloat marginY = (self.navigationController.navigationBar.frame.size.height / 2) - (imageSize.height / 2);

    imageView.frame = CGRectMake(marginX, marginY , imageSize.width, imageSize.height);
    [self.navigationController.navigationBar addSubview:imageView];
 }

【问题讨论】:

    标签: ios objective-c xcode uinavigationcontroller


    【解决方案1】:

    请将 centerX 更新为

    CGFloat marginX = (self.navigationController.navigationBar.frame.size.width - imageSize.width) / 2;
    

    或者

    CGFloat marginX = (self.navigationController.navigationBar.frame.size.width/2) - (imageSize.width / 2);
    

    【讨论】:

    • 我想以自定义标题为中心,而不是以导航栏为中心。
    【解决方案2】:

    我认为,更好的解决方案是使用custom view 作为导航栏的标题。

    UIView* customViewWithImage = [self createCustomView];
    self.navigationItem.titleView = customViewWithImage;
    

    您可以从title attributes 属性中获取标题的属性,也可以从appearance 中获取此信息。

    【讨论】:

      【解决方案3】:

      像这样使用它,

      创建您的自定义视图并在您的自定义视图中添加标签和图像,并将此自定义视图添加为 titleView

      UIView *vw = [[UIView alloc] initWithFrame:yourFrame];
      UILabel *lbl = [[UILabel alloc] initWithFrame:lblFrame];
      UIImageView *imgView = [[UIImageView alloc] initWithFrame:imgFrame];
      [vw addSubView:lbl];
      [vw addSubView:imgView];
      self.navigationItem.titleView = vw;
      

      【讨论】:

        猜你喜欢
        • 2012-11-28
        • 2020-12-29
        • 1970-01-01
        • 2013-11-16
        • 2019-05-26
        • 1970-01-01
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多