0

我正在使用 iOS 6.1,并希望在视图加载时以编程方式将标题为“Info”的自定义宽度的 UIBarButtonItem 添加到 UINavigationItem。我不想使用图像来实现这一点。

我阅读了几个关于如何更改 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;
}

这段代码有什么问题?

4

2 回答 2

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;
于 2013-08-21T04:00:46.103 回答
0

you can also add button just like this..

 - (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;
    }
于 2013-08-21T04:50:42.403 回答