Reputation: 20289
I want to set a text on the position of leftBarButtonItem
/rightBarButtonItem
in the UINavigationBar
. You have to use UIBarButtonItem
, but you can put different UIView
objects into it. First I tried to use a label, but that doesn't work. The code is in C#, but you should get the idea:
UILabel textLabel = new UILabel();
textLabel.Text = "My custom text which should be displayed in navigation bar";
UIBarButtonItem customBarButtonItem = new UIBarButtonItem (textLabel);
NavigationItem.RightBarButtonItem = customBarButtonItem;
The label is not shown. If I use a button it seems to work (except the styling has to be adapted).
UIBarButtonItem customBarButtonItem = new UIBarButtonItem ("My custom text which should be displayed in navigation bar", UIBarButtonItemStyle.Plain,null);
NavigationItem.RightBarButtonItem = customBarButtonItem;
Why isn't it possible to use a UILabel
? What is the correct way of showing a text like a header in a UIBarButtonItem
?
Edit:
My current findings are:
Either set the title of UIBarButtonItem
or set the frame of UILabel
(thanks to Anbu.Karthik for this).
Upvotes: 0
Views: 163
Reputation: 82766
change
UILabel testLabel = new UILabel();
testLabel.frame=CGRectMake(0, 0, 200, 21);
testLabel.Text = "yuhu";
UIBarButtonItem test = new UIBarButtonItem (testLabel.text);
Upvotes: 1
Reputation: 3690
Change this line of code 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;
Upvotes: 1
Reputation: 5388
Use this
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;
Upvotes: 0