我有一个可以在屏幕上拖动的按钮。我想知道是否有办法将按钮保持在视图的框架内。
我已经使用此代码来拖动按钮:
UIPanGestureRecognizer *buttonPanRecognizer;
buttonPanRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(setObjectLocation:)];
[NewButton addGestureRecognizer:buttonPanRecognizer];
- (void)setObjectLocation:(UIPanGestureRecognizer *)recognizer {
CGPoint location = [recognizer locationInView:self.view];
if (CGRectContainsPoint([NewButton frame], location)) { // NewButton
NewButton.center = location;
}
else if (CGRectContainsPoint([NewLabel frame], location)) { // NewLabel
NewLabel.center = location;
} }
我也希望能够保留其他类型的物品。
Thansk提前:)
问题是可以在屏幕外拖动部分UIButton。
答案 0 :(得分:1)
我必须同意你的问题不太清楚。什么是标签应该的东西。通常,要将按钮保留在框架内,您已经拥有了所需的一切:
UIPanGestureRecognizer* buttonPanRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(setObjectLocation:)];
[NewButton addGestureRecognizer:buttonPanRecognizer];
- (void)setObjectLocation:(UIPanGestureRecognizer *)recognizer {
CGPoint location = [recognizer translationInView:self.view];
if (CGRectContainsPoint(self.view.frame, location)) {
NewButton.center = location;
}
}
答案 1 :(得分:0)
有什么问题?只需将按钮的原点保持在rect(frame.x,frame.y,frame.width - button.width,frame.height - button.height)中。