2012-01-18 49 views
1

我想製作一個自定義的UIBarButtonItem來表示完成按鈕。 我想使應用程序國際化,所以我希望文本可以直接編輯。要考慮「完成」標籤的不同長度,我設計了一個StretchableImage。是否有可能直接更改默認的編輯按鈕背景或是需要自定義的UIBarButtonItem?如果是這樣,根據標籤長度動態調整背景拉伸圖片大小的方法是什麼?更改完成UIBarButtonItem的背景圖像

回答

7

如果您僅針對iOS 5.0,則可以使用新的UIAppearance方法更改默認外觀,具體爲-setBackButtonBackgroundImage:forState:barMetrics:

如果您需要支持舊版本的iOS,你應該繼承UIBarButtonItem,加UIButton實例變量,創建並在UIBarButtonIteminit方法調用–initWithCustomView:。這是因爲UIBarButtonItem不是UIView的子類,您不能在其中繪製自定義圖像。您還應該手動設置UIBarButtonItemwidth屬性。

@interface MYCustomBarButtonItem : UIBarButtonItem 
{ 
    UIButton *button; 
} 
- (id)initWithTitle:(NSString *)title; // name it in concordance with your needs 
@end 

#define kButtonHeight 30 
#define kButtonTitleFontSize 12 
#define kButtonTitlePadding 5 

@implementation MYCustomBarButtonItem 

- (id)initWithTitle:(NSString *)title 
{ 
    button = [UIButton buttonWithType:UIButtonTypeCustom]; // add retain here, and write the dealloc method if you aren't using ARC. Also, release it if self == nil. 
    self = [super initWithCustomView:button]; 
    if (self) { 
     UIFont *titleFont = [UIFont boldSystemFontOfSize:kButtonTitleFontSize]; 
     CGSize titleSize = [title sizeWithFont:titleFont]; 
     CGFloat buttonWidth = titleSize.width + kButtonTitlePadding * 2; 
     button.frame = CGRectMake(0, 0, buttonWidth, kButtonHeight); 
     self.width = buttonWidth; 

     [button setTitle:title forState:UIControlStateNormal]; 

     // Set your styles 
     button.titleLabel.font = titleFont; 

     // Normal state background 
     UIImage *backgroundImage = ...; // create your normal stretchable background image 
     [button setBackgroundImage:backgroundImage forState:UIControlStateNormal]; 

     // Pressed state background 
     backgroundImage = ...; // create your pressed stretchable background image 
     [button setBackgroundImage:backgroundImage forState:UIControlStateHighlighted]; 

     // and so on... 
    } 
    return self; 
} 

@end 

PS。不要忘記覆蓋您的子類的targetaction屬性,以便與button實例配合使用。

+0

如何根據文字的寬度來調整按鈕大小。另外,你如何將背景設置爲StretchableImage?謝謝。 – 2012-01-18 21:15:39

+0

您可以使用'NSString'的'-sizeWithFont:'方法:http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html。背景是用'UIButton'的'-setBackgroundImage:forState:'設置的。 – 2012-01-18 21:19:59

+0

@ibeitia,我爲你更新了代碼。 – 2012-01-18 21:46:38

2

我可能誤解了你的問題,但我相信所有你想要的是這樣的:

UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithTitle:@"I am done" style:UIBarButtonItemStyleBordered target:self action:nil]; 
UIImage *stretchable = [[UIImage imageNamed:@"StretchableImage.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:16]; 
[btnDone setBackgroundImage:stretchable forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; 
[self.navigationItem setRightBarButtonItem:btnDone]; 

一個的UIBarButtonItem並自動調整它的寬度與標籤的寬度。

+0

@Stanislav Yaglo是對的。此解決方案僅適用於iOS 5.如果您要定位舊版本,則需要製作UIBarButtonItem的簡單子類。 – simonbs 2012-01-18 21:04:40