2011-09-22 72 views
2

我想動畫像TheElements示例項目一樣UIBarButtonItem。 我很確定我必須使用customView屬性,但我不想使用圖像來做到這一點,因爲我需要用一些本地化字符串(多語言)來更改標題。 那麼有可能創建一個UIButton,它看起來像一個UIBarButtonItem如何動畫UIBarButtonItem

回答

2

這是代碼。

NSArray *images = [NSArray arrayWithObjects: 
     [UIImage imageNamed:@"image0.png"], 
     [UIImage imageNamed:@"image1.png"], 
     nil]; 

imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image0.png"]]; 
imageView.animationImages = images; 

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; 
button.bounds = self.imageView.bounds; 
[button addSubview:self.imageView]; 
[button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; 

UIBarButtonItem * barButton = [[[UIBarButtonItem alloc] initWithCustomView: button] autorelease]; 

有些事情需要注意:

UIButton是面積爲零,因爲它不具有在初始化設置它的邊界,從而邊界與UIImageView的界限(它有它的邊界初始化初始化從圖像中)。

UIButton處理觸摸事件的動作/目標。沒有設置UIBarButtonItem的操作/目標。

要動畫:

[imageView startAnimating]; 
+0

閱讀我的問題到最後..我已經注意到我不想使用UIImageView解決方案,因爲我必須通過本地化字符串設置一些標題。所以我想知道如何使用UIButton創建一個UIBarButtonItem – klefevre

0

的SWIFT-3.X 創建的UIBarButtonItem IBOutlet中和實施didSet如下

@IBOutlet weak var leftMenuBtn: UIBarButtonItem! { 
     didSet { 
      let icon = UIImage(named: "myCustomIcon") 
      let iconSize = CGRect(origin: .zero, size: icon!.size) 
      let iconButton = UIButton(frame: iconSize) 
      iconButton.setBackgroundImage(icon, for: .normal) 
      leftMenuBtn.customView = iconButton 

      iconButton.addTarget(self, action:#selector(leftMenuClicked(_:)), for: .touchUpInside) 
     } 
    } 

然後實現選擇方法,用於上面創建左菜單按鈕

func leftMenuClicked(_ sender: Any) { 
    /* Following is the code to animate ButtonView by rotation of 90 degrees, 
just replace with your own custom animation. */ 

    var transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2)) 
    UIView.animate(withDuration: 0.5) { 
     self.leftMenuBtn.customView!.transform = transform 
    } 
}