簡體   English   中英

iOS:動畫UIButton的文本位置不起作用

[英]iOS: Animating text position of UIButton doesn't work

當按下“錯誤答案”按鈕時,我希望按鈕的文本“消失”。

在我的問題 - 演示代碼中,我的項目有兩個按鈕,一個帶有插座'myBtn'而沒有任何動作,另一個帶有TouchUpInside動作。 動作處理程序如下所示:

- (IBAction)goPressed:(UIButton*)sender {

//UILabel *lbl = self.myBtn.titleLabel;
UILabel *lbl = sender.titleLabel;
[UIView animateWithDuration:1.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     lbl.center = CGPointMake(lbl.center.x-60, lbl.center.y);
                     lbl.alpha = 0;
                 }
                 completion:nil];
}

我試圖動畫兩個屬性:'alpha'從1到0,文本位置向左移動60個點。

如果我取消注釋第一個“UILAbel”行並注釋第二個,那么按下按鈕會在第二個按鈕中運行一個漂亮的動畫。

但是,如果我將代碼保留為顯示,嘗試為按下的按鈕本身設置動畫,則alpha動畫效果很好,但位置不會改變。

任何幫助將非常感謝!

我在iOS7上看到過這種問題。 在IBAction中運行良好的動畫在iOS7上不起作用。 我不得不將所有動畫代碼移動到另一個方法,並在延遲后調用選擇器。 如果你這樣做,你的代碼將正常工作 -

- (IBAction) goPressed:(UIButton*)sender {
[self performSelector:@selector(animateButton:) withObject:sender afterDelay:0.1];
}

- (void) animateButton:(UIButton *) button{
UILabel *lbl = button.titleLabel;
[UIView animateWithDuration:1.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     lbl.center = CGPointMake(lbl.center.x-60, lbl.center.y);
                     lbl.alpha = 0;
                 }
                 completion:nil];
}

你的問題是將UIButtonUILabel混合在一起。

在這種情況下,方法參數(UIButton*)sender引用UIButton 原因UILabel *lbl = sender.titleLabel; 不起作用是因為senderUIButton引用。 要訪問標簽對象,必須引用該UILabel嵌入UIButton通過hirarchy sender > UIButton > UILabel

所以你應該使用的代碼是:

UIButton *button = sender;
UILabel *lbl = sender.titleLabel;
[UIView animateWithDuration:1.0
                  delay:0.0
                options:UIViewAnimationOptionCurveEaseOut
             animations:^{
                 lbl.center = CGPointMake(lbl.center.x-60, lbl.center.y);
                 lbl.alpha = 0;
             }
         completion:nil];
}

出現代碼的原因是因為alphaUIButtonUILabel的屬性。 因此即使您錯誤地重新sender也會有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM