Iphone 如何在不使用图像的情况下以编程方式将自定义宽度的UIBarButtonim添加到UINavigationItem

Iphone 如何在不使用图像的情况下以编程方式将自定义宽度的UIBarButtonim添加到UINavigationItem,iphone,ios,ios6,width,uibarbuttonitem,Iphone,Ios,Ios6,Width,Uibarbuttonitem,我正在使用iOS 6.1,希望在加载视图时以编程方式将标题为“Info”的自定义宽度为的UIBarButtonim添加到UINavigationItem我不想使用图像来实现这一点。 我读了几篇关于如何改变一个uibarbuttonite的宽度的文章,但似乎没有一篇适合我 我尝试了此操作,但按钮未显示: - (void)viewDidLoad { UIView *infoButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,

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

我读了几篇关于如何改变一个uibarbuttonite的宽度的文章,但似乎没有一篇适合我

我尝试了此操作,但按钮未显示:

- (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;
}

此代码有什么问题?

您也可以像这样添加按钮

//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;
 - (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;
    }

这很好,但是按钮现在是一个绿色矩形。如何添加原始按钮的外观和感觉?我只想更改宽度。添加属性,如颜色、边框或其他属性以添加外观,您可以使用此UIButton*searchButton执行任何操作,就像使用普通按钮一样。添加标准条形按钮项的所有属性(可以从对象库拖放到情节提要上的属性)为所有不同的状态创建一个自定义的并不是一项简单的任务。我很惊讶没有更简单的方法来简单地更改width属性。这很好,但是按钮现在是一个红色矩形。如何添加原始按钮的外观和感觉?我只想更改width.UIView*infoButtonView=[[UIView alloc]initWithFrame:CGRectMake(0,20,100,44)];[infoButtonView setBackgroundColor:[UIColor clearColor]];UIButton*button1=[UIButton Button类型为:UIButtonyPeroundRect];[按钮1设置框:CGRectMake(0,15,90,21)];按钮1.backgroundColor=[UIColor clearColor];[按钮1设置标题:@“信息”用于状态:uicontrol状态正常];按钮1.backgroundColor=[UIColor clearColor];[信息按钮视图添加子视图:按钮1];UIBarButtonItem*infoButton2=[[UIBarButtonItem alloc]initWithCustomView:infoButtonView];self.navigationItem.rightBarButtonItem=infoButton2;