【问题标题】:UIBarButtonItem width with a two-line label带有两行标签的 UIBarButtonItem 宽度
【发布时间】:2017-10-01 14:03:31
【问题描述】:

我想知道如何从 UIBarButtonItem 中的两行标签中去掉左右空格,它的视图由 setCustomView 设置如下:

UIButton* forwardButton = [UIButton buttonWithType:101];

[forwardButton setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];
[forwardButton.titleLabel setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];

[forwardButton setTitle:@"Now\nPlaying" forState:UIControlStateNormal];
[forwardButton addTarget:self action:@selector(openPlayer) forControlEvents:UIControlEventTouchUpInside];

[forwardButton.titleLabel setNumberOfLines:2];
[forwardButton.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
[forwardButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
[forwardButton.titleLabel setFont:[UIFont boldSystemFontOfSize:10]];

[navButton setCustomView:forwardButton];

Here 是我得到的结果。

按钮的宽度就像标签在一行中写有文字一样,例如this

【问题讨论】:

    标签: iphone ios objective-c uinavigationbar uibarbuttonitem


    【解决方案1】:

    您可以尝试更改按钮的边界。

    UIButton* forwardButton = [UIButton buttonWithType:101];
    [forwardButton setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];
    [forwardButton.titleLabel setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];
    
    [forwardButton setTitle:@"Now\nPlaying" forState:UIControlStateNormal];
    [forwardButton.titleLabel setNumberOfLines:2];
    [forwardButton.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
    [forwardButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [forwardButton.titleLabel setFont:[UIFont boldSystemFontOfSize:10]];
    
    forwardButton.bounds = CGRectMake(0, 0, 30, 30);
    
    
    UIBarButtonItem* forwardButtonItem = [[UIBarButtonItem alloc] initWithCustomView: forwardButton];
    self.navigationItem.rightBarButtonItem = forwardButtonItem;
    

    对此进行了测试并有效

    【讨论】:

    • 谢谢,确实有效,我在设置标题之前尝试设置边界 =___="
    • 又出现了一个问题。该解决方案仅适用于导航栏样式设置为默认值,如果我尝试黑色,宽度问题会再次出现。尝试在解决方案代码之前和之后设置样式以及在 Interface Builder 中设置它。
    【解决方案2】:
    NSString   *titleStr=@"Now\Playing";
    BarButton.titleLabel setLineBreakMode:UILineBreakModeWordWrap];
    
    [BarButton setTitle:titleStr forState:UIControlStateNormal];
    

    【讨论】:

    • @AlimovAndrei- 使用 BarButton.titleLabel.numberOfLines = 0
    • 将行设置为 0 不会改变任何东西,您给出的答案中标签的呈现效果有效,但 Bogus 给出的答案更简单
    猜你喜欢
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多