导航栏中的自定义文本

时间:2015-09-07 08:08:42

标签: ios uilabel uinavigationbar uibarbuttonitem uinavigationitem

我想在leftBarButtonItem中设置rightBarButtonItem / UINavigationBar位置的文字。您必须使用UIBarButtonItem,但可以将不同的UIView对象放入其中。首先,我尝试使用标签,但这不起作用。代码在C#中,但你应该明白这个想法:

UILabel textLabel = new UILabel();
textLabel.Text = "My custom text which should be displayed in navigation bar";
UIBarButtonItem customBarButtonItem = new UIBarButtonItem (textLabel);
NavigationItem.RightBarButtonItem = customBarButtonItem;

标签未显示。如果我使用按钮它似乎工作(除了必须调整样式)。

UIBarButtonItem customBarButtonItem = new UIBarButtonItem ("My custom text which should be displayed in navigation bar", UIBarButtonItemStyle.Plain,null);
NavigationItem.RightBarButtonItem = customBarButtonItem;

为什么不能使用UILabel?在UIBarButtonItem中显示文字的正确方法是什么?

修改

我目前的发现是:

设置UIBarButtonItem的标题或设置UILabel的框架(感谢Anbu.Karthik)。

3 个答案:

答案 0 :(得分:1)

更改

UILabel testLabel = new UILabel();
testLabel.frame=CGRectMake(0, 0, 200, 21);

testLabel.Text = "yuhu";
UIBarButtonItem test = new UIBarButtonItem (testLabel.text);

答案 1 :(得分:1)

更改此行代码UIBarButtonItem test = new UIBarButtonItem (testLabel);

UILabel testLabel = new UILabel();
testLabel.Text = "yuhu";
 testLabel.frame=CGRectMake(x, y, width, height);
//change this line

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:testLabel];
NavigationItem.RightBarButtonItem = test;

答案 2 :(得分:0)

使用此

UIImage *buttonImage = [UIImage imageNamed:@"back.png"];
 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 [button setImage:buttonImage forState:UIControlStateNormal];
 button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
 [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

 UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
 self.navigationItem.leftBarButtonItem = customBarItem;