IOS 實現可移動拖拽的View

2021-06-17 18:54:29 字數 1608 閱讀 7689

在乙個大的view中,某個view元素可以在該view中自由拖動,但是不能超出該大view範圍。

首先新增拖動gesture:

uipangesturerecognizer *pangesturerecognizer = [[uipangesturerecognizer alloc] initwithtarget:self action:@selector(dragreplybutton:)];

[self.addreplyview addgesturerecognizer:pangesturerecognizer];

[pangesturerecognizer release];

拖拽方法具體實現:

- (void)dragreplybutton:(uipangesturerecognizer *)recognizer  else if (recognizer.state == uigesturerecognizerstatechanged) 

cgpoint translation = [recognizer translationinview:self];

recognizer.view.center = cgpointmake(recognizer.view.center.x + translation.x,recognizer.view.center.y + translation.y);

[recognizer settranslation:cgpointzero inview:self];

} else if (recognizer.state == uigesturerecognizerstateended || recognizer.state == uigesturerecognizerstatecancelled) else if ((currentframe.origin.y + currentframe.size.height) > self.bounds.size.height)

[uiview animatewithduration:0.5 animations:^];

return;

}if ((currentframe.origin.x + currentframe.size.width) > self.bounds.size.width) else if ((currentframe.origin.y + currentframe.size.height) > self.bounds.size.height)

[uiview animatewithduration:0.5 animations:^];

return;

}if (currentframe.origin.y < 0) ];

return;

}if ((currentframe.origin.y + currentframe.size.height) > self.bounds.size.height) ];

return;}}

}

其中- (cgpoint)translationinview:(uiview *)view可以得到現有的被拖動view相對於引數view的位置,如果x,y小於0,則不能拖動

對於拖出的情況,做動畫把view拉進來。

自定義可拖拽view

我們知道view的繪製有三個重要的過程分別是measure,layout,draw.measure負責測量view的尺寸,layout負責定位view的位置,draw負責把view繪製到上。我們這就是通過layout重新定位view。public class custommoveview exten...

iOS開發之實現可拖拽懸浮按鈕

原理 在按鈕上新增拖拽手勢uipangesturerecognizer,獲取手勢移動的偏移值,然後重新設定按鈕的位置為按鈕位置加上偏移值。注意拖拽位置不要超出螢幕位置。最後移除手勢是現在在arc記憶體管理模式的規範 風格,類似的有在dealloc裡面移除通知 定時器。因為以前在mrc時候是手動建立記...

實現 元素 可拖拽

css部分 body drag item html部分 drag item div js部分 var dragitem document.getelementsbyclassname drag item 0 var divx,divy,startmou startmousey,endmou endm...