对齐UIBarButtonItem标题以防止其他按钮重叠?

时间:2015-04-23 20:06:21

标签: ios user-interface interface-builder xcode-storyboard

我想创建一个标题工具栏,如下图所示。它来自Twitter应用程序的Web视图。

enter image description here

我创建了一个UIToolbar并将其放在顶部。然后我左右插入按钮并更改了标识符以获得正确的符号。

我的问题是中间的文字。我创建了一个UIBarButtonItem并将其放在按钮之间。这是我的问题。

  • 当标题要长时,如何实现UIBarButtonItem标题不会与左右按钮重叠?

就我而言:

enter image description here

  • 如果标题变长,我如何实现标题最终得到...
  • 如何设置子标题?
  • 如何实现按钮不可点击,即颜色为黑色?

编辑使用@Viral Savaj的答案:这是它的样子:

enter image description here

3 个答案:

答案 0 :(得分:1)

  1. 要测试标题是否太长,您应该使用字符计数。让myHeaderBarString代表标题的字符串。您可能需要调整此数字以在截断之前找到合适的长度。
  2. if count(myHeaderBarString) > 40 {
    
    myHeaderBarString = myHeaderBarString.substringToIndex(40)
     myHeaderBarString.append("...") 
    
    }
    

    对于字幕,您应该在其中插入一个带有UILabel的新视图。

答案 1 :(得分:0)

您可以像这样将自定义标题视图设置到导航栏。

//To hide default back button
self.navigationItem.hidesBackButton=YES;

//Title View for Navigation
UIView *navTitle1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
[navTitle1 setBackgroundColor:[UIColor lightGrayColor]];

//Left View button and separator
UIButton *crossBarButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[crossBarButton setTitle:@"X" forState:UIControlStateNormal];

//Center view with two buttons and seprator for them
UILabel *topTitle =  [[UILabel alloc] initWithFrame: CGRectMake(50,0, self.view.bounds.size.width-100, 22)];
topTitle.text = @"text"; 
topTitle.font = [UIFont systemFontOfSize:25];
topTitle.lineBreakMode = NSLineBreakByCharWrapping;


UILabel *subTitle =  [[UILabel alloc] initWithFrame: CGRectMake(50,20, self.view.bounds.size.width-100, 18)];
subTitle.text = @"subtext"; 
subTitle.font = [UIFont systemFontOfSize:18];
subTitle.lineBreakMode = NSLineBreakByCharWrapping;

//Right button with seprator before that
UIButton *uploadBarButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-50, 0, 44, 44)];
[uploadBarButton setTitle:@"U" forState:UIControlStateNormal];


[navTitle1 addSubview:crossBarButton];
[navTitle1 addSubview:topTitle];
[navTitle1 addSubview:subTitle];
[navTitle1 addSubview:uploadBarButton];
self.navigationItem.titleView = navTitle1;

您可以参考THIS了解更多详情。

答案 2 :(得分:0)

使用BarButtonItem.customView,它有效。

let button = UIButton(frame: CGRectMake(0,0,200,40))

button.titleLabel?.adjustsFontSizeToFitWidth = true

button.setTitle("gogogogogogogogoogogogogogogogogogoogo", forState: .Normal)

button.setTitleColor(UIColor.blackColor(), forState: .Normal)

button.addTarget(self, action: "showMessage:", forControlEvents: .TouchUpInside)

let rightBarButtonItem = UIBarButtonItem()

rightBarButtonItem.customView = button

self.navigationItem.rightBarButtonItem = rightBarButtonItem