我正在使用iOS 6.1,并希望在加载视图时以编程方式向UINavigationItem添加标题为“Info”的自定义宽度的UIBarButtonItem。 我不想使用图片来实现这一目标。
我阅读了几个关于如何更改UIBarButtonItem宽度的线程,似乎没有一个对我有效。
我尝试了这个,但按钮没有出现:
- (void)viewDidLoad
{
UIView *infoButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
UIBarButtonItem *infoButton2 = [[UIBarButtonItem alloc] initWithCustomView:infoButtonView];
[infoButton2 setStyle:UIBarButtonItemStyleBordered];
[infoButton2 setTitle:@"Info"];
self.navigationItem.rightBarButtonItem = infoButton2;
}
这段代码出了什么问题?
答案 0 :(得分:2)
//This worked for me
UIButton *searchButton =[[UIButton alloc]init];
searchButton.frame=CGRectMake(0, 0, 200, 40);
[searchButton setTitle:@"Info" forState:UIControlStateNormal];
searchButton.backgroundColor= [UIColor greenColor];
[searchButton addTarget:self action:@selector(onFilter) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *searchBarButton=[[UIBarButtonItem alloc] initWithCustomView:searchButton] ;
self.navigationItem.rightBarButtonItem = searchBarButton;
答案 1 :(得分:0)
您也可以像这样添加按钮..
- (void)viewDidLoad
{
UIView *infoButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 50, 44)];
[infoButtonView setBackgroundColor:[UIColor clearColor]];
UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(0,15,45,21)];
[button1 setTitle:@"Info" forState:UIControlStateNormal];
button1.backgroundColor=[UIColor redColor];
[infoButtonView addSubview:button1];
UIBarButtonItem *infoButton2 = [[UIBarButtonItem alloc] initWithCustomView:infoButtonView];
self.navigationItem.rightBarButtonItem = infoButton2;
}