为自定义UIBarButtonItem设置文本

时间:2012-05-24 08:57:56

标签: iphone uibarbuttonitem

我需要为Custom UIBarButtonItem设置标题。

我有以下代码:

UIButton* backToRecent = [UIButton buttonWithType:UIButtonTypeCustom];
[backToRecent setImage:[UIImage imageNamed:@"back.png"]forState:UIControlStateNormal];

[backToRecent addTarget:self action:@selector(backToRecent) forControlEvents:UIControlEventTouchUpInside];
[backToRecent setFrame:CGRectMake(0, 0, 60, 30)];

UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backToRecent];
[backButtonItem setTitle:@"Recent"];
partViewController.navigationItem.leftBarButtonItem = backButtonItem;
[backButtonItem release];

但按钮显示时没有“最近”文字。

2 个答案:

答案 0 :(得分:18)

穆罕默德,我怀疑你已经解决了这个问题,但这是一个简单的方法。希望这可以帮助那些正在努力解决同一问题的人:

    UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Recent" style:UIBarButtonItemStyleBordered target:self action:@selector(backToRecent)];
    self.navigationItem.leftBarButtonItem = backButtonItem;

答案 1 :(得分:7)

你应该在UIButton上设置标题,而不是UIBarButtonItem

[backToRecent setTitle:@"Recent" forState:UIControlStateNormal];

并且使变量和方法的名称相同并不好

[backToRecent addTarget:self action:@selector(backToRecent) forControlEvents:UIControlEventTouchUpInside];

它不起作用,因为你使用

[backToRecent setImage:[UIImage imageNamed:@"back.png"]forState:UIControlStateNormal];

尝试使用

[backToRecent setBackgroundImage:[UIImage imageNamed:@"back.png"]forState:UIControlStateNormal];