2011-07-29 60 views
0

這是用圖像分配和初始化UIBarButton項目的正確方法嗎?如何創建(alloc/initwithImage)UIBarButtonItem?

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc]initWithImage:@"back_topbtn.png" style:UIBarButtonItemStyleDone target:nil action:nil]; 
+3

認爲正確的。但爲什麼不採取行動?不採取行動你會用按鈕做什麼? – karim

回答

3

不,這不是正確的方法,不使用圖像對象,你把你的圖片名稱here.so這顯示一個警告你

UIBarButtonItem *barBtn = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_topbtn.png"] style:UIBarButtonItemStyleDone target:nil action:nil] autorelease]; 

這是使用它的正確方法,當你沒有宣佈任何行動時,這也只不過是一張圖片。所以聲明任何操作(使用選擇器)。

1

正確的方法是使用UIImage。在你的- initWithNibName:bundle:方法中這樣做是有道理的。

以下是添加一個圖像按鈕的例子。請注意,當點擊該按鈕時將調用myButtonTapped:,請務必執行該操作。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     self.title = @"My title"; 

     UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"myimage.png"] style:UIBarButtonItemStylePlain target:self action:@selector(myButtonTapped:)]; 
     self.navigationItem.rightBarButtonItem = myButton; 
     [myButton release]; 
    } 
    return self; 
} 
2
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
UIImage *btnImg = [UIImage imageNamed:@"some_image-name"]; 
[btn setImage:btnImg forState:UIControlStateNormal]; 
btn.frame = CGRectMake(0, 0, btnImg.size.width, btnImg.size.height); 
[btn addTarget:self action:@selector(whatever) forControlEvents:UIControlEventTouchUpInside]; 
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];