2016-01-13 33 views
0

如何停止正在移動的UIView? 或正在減速的視圖。如何停止正在移動的UIView?

的問題是,例如:

我有一個方法變更後的按鈕的點擊事件視圖的位置;同時另一個拖動事件可以改變視圖的位置。如果我先讓拖動事件發生,那麼當視圖減速時,快速點擊B,視圖的位置會根據B後面的方法改變,但它會立即返回到正在減速並繼續減速的位置。該視圖不會回到按鈕B所指示的位置,即使它完成減速。

代碼如下。

首先,我使用KVO使視圖(即_topView是代碼)響應tableView的contentOffset(在tableView被拖動時,視圖將移動)。

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
change:(NSDictionary<NSString *,id> *)change context:(void *)context 

{ 
    CGPoint contentOffset = [change[NSKeyValueChangeNewKey] CGPointValue]; 

    CGRect topFrame = _topView.frame; 

    topFrame.origin.y = -(contentOffset.y + TOP_SECTION_HEIGHT); 
    _topView.frame = topFrame; 
} 

然後在buttonB被點擊時,下面的動畫將被觸發。

topFrame = CGRectMakke(...); 
[UIView animateWithDuration:1 animations:^{ 
     _topView.frame = topFrame;//topView 
     targetTableView.contentOffset = targetViewTargetOffset; 
    }]; 
+2

顯示您的'UIView'「移動」代碼。 – Raptor

+1

KVO不是動畫視圖的好方法。爲什麼你不只是在動畫塊中一起製作動畫? – SmokeDispenser

+0

@JanGreve因爲我必須使視圖與tableView一起移動,即使後者正在減速 – WhiteTherewasproblem

回答

0

正如我所理解的問題,你應該停止tableview減速,然後調用按鈕事件的方法。 按下按鈕時停止減速:

-(IBAction)buttonPressed:(id)sender 
{ 
    //this will stop table view animations 
    [targetTableView setContentOffset:targetTableView.contentOffset animated:NO]; 
    //then you can adjust the frame of a view accurately 
    topFrame = CGRectMakke(...); 
[UIView animateWithDuration:1 animations:^{ 
     _topView.frame = topFrame;//topView 
     targetTableView.contentOffset = targetViewTargetOffset; 
    }]; 
} 
+0

謝謝,這解決了我的問題。順便說一句,另一種方法是放棄KVO,因爲它的代碼不會執行tableView移動或減速。 – WhiteTherewasproblem

0

試試這個代碼將有益的給你:

[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationBeginsFromCurrentState:YES]; 
[UIView setAnimationDuration:0.1]; 
[UIView setAnimationCurve: UIViewAnimationCurveLinear]; 
// other animation properties 

// set view properties 

[UIView commitAnimations]; 
0

爲什麼你的觀點是感動?要點是,如果它只是一個審美動畫,您可以使用-snapshotViewAfterScreenUpdates:創建視圖的副本,隱藏您的原始視圖並將此快照移到最重要的位置,然後刪除快照並將原始視圖移動到動畫的結束位置。這是一個有點內存/電池昂貴,但你的動畫是完全獨立於你的KVO代碼。

如果它是一個更重要的組件,在交互性更強的情況下,您應該爲您的KVO添加一個標誌(例如:isAnimated)以防止動畫啓動時位置發生變化。

正如@Fogmeister所說,KVO不是動畫的最佳選擇,因爲他們有一個代表(scrollviewDidScroll),所以更多地使用滾動視圖。