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

Align UIBarButtonItem Title to prevent overlapping of other Buttons?

我想创建一个如下图所示的 header 工具栏。它来自 Twitter 应用程序的网页视图。

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

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

就我而言:

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

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

myHeaderBarString = myHeaderBarString.substringToIndex(40)
 myHeaderBarString.append("...") 

}

对于字幕,您应该插入一个新视图,其中包含 UILabel。

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

//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了解更多详情。

使用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