无法将条形按钮添加到UIToolBar

时间:2013-10-19 12:48:09

标签: iphone ios objective-c

我想在我的应用程序中创建一个静态页脚。我用过UIToolbar。现在我想添加一些带有自定义照片的按钮。工具栏工作正常,但不显示按钮。

以下是我用来添加按钮的代码:

UIImage *facebookImage=[[UIImage alloc]initWithContentsOfFile:@"facebook.png"];
UIImage *twitterImage=[[UIImage alloc]initWithContentsOfFile:@"twitter.png"];
UIImage *messageImage=[[UIImage alloc]initWithContentsOfFile:@"message.png"];
UIImage *emailImage=[[UIImage alloc]initWithContentsOfFile:@"email.png"];


UIBarButtonItem *facebook=[[UIBarButtonItem alloc]initWithImage:facebookImage style:UIBarButtonItemStyleBordered target:Nil action:Nil];
UIBarButtonItem *twitter=[[UIBarButtonItem alloc]initWithImage:twitterImage style:UIBarButtonItemStylePlain target:Nil action:Nil];
UIBarButtonItem *message=[[UIBarButtonItem alloc]initWithImage:messageImage style:UIBarButtonItemStylePlain target:Nil action:Nil];
UIBarButtonItem *email=[[UIBarButtonItem alloc]initWithImage:emailImage style:UIBarButtonItemStylePlain target:Nil action:Nil];

NSArray *toolbarButtons = [NSArray arrayWithObjects: facebook, twitter,email,message, nil];
[Footer setItems:toolbarButtons];

2 个答案:

答案 0 :(得分:2)

在您的代码更改中:

UIImage *facebookImage=[[UIImage alloc]initWithContentsOfFile:@"facebook.png"];
UIImage *twitterImage=[[UIImage alloc]initWithContentsOfFile:@"twitter.png"];
UIImage *messageImage=[[UIImage alloc]initWithContentsOfFile:@"message.png"];
UIImage *emailImage=[[UIImage alloc]initWithContentsOfFile:@"email.png"];

with:

UIImage *facebookImage= [UIImage imageNamed:@"facebook.png"];
UIImage *twitterImage= [UIImage imageNamed:@"twitter.png"];
UIImage *messageImage= [UIImage imageNamed:@"message.png"];
UIImage *emailImage= [UIImage imageNamed:@"email.png"];

如果您想使用- (id)initWithContentsOfFile:(NSString *)path方法,您应该获得该文件的完整路径名:

NSString* Path = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"]; 

答案 1 :(得分:0)

在以下代码中,我添加了两个UIBarButton flexSpace ..
您可以根据需要添加UIBarButton

UIToolbar *Toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    Toolbar = UIBarStyleBlackTranslucent;
    [Toolbar sizeToFit];

     NSMutableArray *barItems = [[NSMutableArray alloc] init];
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];

    UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(Cancel)];
    [barItems addObject:btnCancel];

    UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(done)];
    [barItems addObject:btnDone];

    [Toolbar setItems:barItems animated:NO];

点击按钮

时,会调用以下方法
-(void)Cancel
{
  // Write Code for Cancel Method
}

-(void)done
{
  // Write Code for Done Method
}

按照我的回答并根据您的要求添加UIBarButtonItem,可能此代码对您有所帮助。