如何将UILabel设为NavigationBar的rightBarButtonItem?

时间:2013-01-04 23:56:19

标签: iphone objective-c ios xcode

任何人都可以帮助我如何将UILabel设为NavigationBar的rightBarButtonItem吗?

我尝试使用UILabel在UIView上执行UIBarButtonItem的initWithCustomView但崩溃了。

3 个答案:

答案 0 :(得分:3)

您可以尝试以下代码。

 UILabel *yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(260,6,55,32)];
  yourLabel.text = @"Ashu";
    [self.navigationController.navigationBar addSubview:yourLabel];

如果有效,请通知..

答案 1 :(得分:2)

以下是一些示例代码:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 65.0, 30.0)];
label.text = @"Text";
barButton = [[UIBarButtonItem alloc] initWithCustomView:label];

然后您只需将“barButton”设置为等于右侧导航项

即可

答案 2 :(得分:1)

执行此操作:

yourButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30) ];
    [yourButton addTarget:self action:@selector(yourmethod:) forControlEvents:UIControlEventTouchUpInside];

    yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 8, 40, 30)];
    yourLabel.text = @"your Text";
    yourLabel.backgroundColor = [UIColor clearColor];
    yourLabel.textColor = [UIColor whiteColor];
    yourLabel.font = [UIFont boldSystemFontOfSize:12.0f];
    [yourLabel sizeToFit];
    [yourButton addSubview:yourLabel];

[yourButton sizeToFit]; 

    yourBarButton = [[UIBarButtonItem alloc] initWithCustomView:yourButton];
     self.navigationItem.rightBarButtonItem = yourBarButton;