0

我想在UINavigationBar的位置leftBarButtonItem/rightBarButtonItem上设置文本。您必须使用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此)的框架上。

+0

您更好地展现真正的代码,并坚持命名约定。这是相当猜测的工作。 –

+0

@HermannKlecker:我编辑了我的问题以获得更多有意义的占位符。该代码是我想以后使用的。只有内容会改变。 – testing

回答

1

变化

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

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

否则检查标签框架是否有必要 –

+0

我看到的唯一构造函数是我在我的问题中使用的构造函数(您需要更多参数)。首先,我试图使用自动布局,导致崩溃,因为他不知道父母。现在我尝试设置框架并将标签显示出来!同样的事情如何与自动布局一起工作?我必须在哪里添加约束条件? UINavigationController的'View'? – testing

+0

如果您在视图中使用的标签,直接,那么你可以对自动布局的事情,但UIBarbutton不以任何链层次underwith,所以在这里只需要移动/标签分配文字栏按钮文本,所以标签帧这里很好 –

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; 
+0

如果我翻译成C#的世界,这是完全一样的线'的UIBarButtonItem测试=新的UIBarButtonItem(testLabel);'如果* BTN *为* testLabel *。或者你的意思是'UIButton'? – testing

+0

我只想显示文字。第一个想法是使用'UILabel',但是这对我没有用。 – testing

+0

但标签不会给予任何意义栏按钮,因为它不会有任何action.areü计划增加挖掘姿态的UILabel – Mukesh

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;