2016-02-26 45 views
0

我爲尺寸爲(30,50)的標籤創建觸摸移動事件。這裏是代碼設置UITouch的移動範圍

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {  
    UITouch *touch = [touches anyObject]; 
    UIView *superView = self.superview; 
} 

但我需要確保標籤只能在超級視圖內移動。換句話說,UILabel在「觸摸」視圖邊緣時將停止移動,如何設置標籤的移動範圍?

+0

您想將標籤移動到觸摸位置嗎? – UlyssesR

+0

你到現在爲止嘗試過什麼?你可以添加到你的問題?我認爲你可能不得不在'touchesMoved'方法中處理移動。 –

+0

@UlyssesR我需要的是使uilabel在觸及其超級視角邊緣時無法移動。 –

回答

0
  1. 標籤設置爲您的觸摸位置
  2. 檢查標籤的幀是否是上海華
  3. 裏面如果是外面,改變幀,並設置userInteractionEnabled爲NO
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{ 
    self.center = [touches.anyObject locationInView:self.superview]; 

    CGRect bounds = self.superview.bounds; 
    CGRect newFrame = self.frame; 

    if (newFrame.origin.x < 0) { 
     newFrame.origin.x = 0; 
     self.userInteractionEnabled = NO; 
    } 
    if (newFrame.origin.y<0) { 
     newFrame.origin.y = 0; 
     self.userInteractionEnabled = NO; 
    } 
    if (newFrame.origin.x + newFrame.size.width > bounds.size.width) { 
     newFrame.origin.x = bounds.size.width - newFrame.size.width; 
     self.userInteractionEnabled = NO; 
    } 
    if (newFrame.origin.y + newFrame.size.height > bounds.size.height) { 
     newFrame.origin.y = bounds.size.height - newFrame.size.height; 
     self.userInteractionEnabled = NO; 
    } 

    self.frame = newFrame; 
} 
+0

感謝您的幫助。我需要的是標籤在外面時不能移動。隨着你的標籤將在移動結束後回來。換句話說,當label.origin.x或y <0時,如何禁用移動? –

+0

你可以看到UIView的屬性'userInteractionEnabled' >默認是YES。如果設置爲NO,則用戶事件(touch,keys)將被忽略並從事件隊列中移除。因此,當label.frame位於其superView之外時,您可以將'userInteractionEnabled'設置爲NO。 – zhubch

+0

userInteractionEnabled仍然不起作用。它不會停止,即使uilabel在外面,直到我停止點擊它。 –