如何检查十字路口按钮
我在UIView
上动态创建按钮。 我可以通过使用此代码如何检查十字路口按钮
- (IBAction)draggedOut: (id)sender withEvent: (UIEvent *) event: (NSSet *)touches {
UIButton *selected = (UIButton *)sender;
selected.center = [[[event allTouches] anyObject] locationInView:hallView];
}
我可以有更多然后一个键拖动来移动它们。当我拖动一些按钮时,我需要检查是否有与其他按钮的交叉点?
我该怎么做?
您应该通过在视图中的其他按钮周期,并为他们每个人,检查是否在相交拖动一个通过:
CGRectIntersectsRect (draggedButton.frame, anotherButton.frame);
你可以使用这样的功能:
- (BOOL)isThereButtonsIntersectionInView:(UIView *)containerView
forButton:(UIButton *)draggedButton
{
for(UIView *view in containerView.subviews){
if([view isKindOfClass:[UIButton class]] &&
view != draggedButton &&
CGRectIntersectsRect (view.frame, draggedButton.frame)){
return YES;
}
}
}
return NO;
}
调用此方法传递为参数包含按钮和拖动的按钮的视图。
你可以得到按钮的框架,并检查使用此
if(CGRectIntersectsRect(firstButton.frame, secondButton.frame)) {
return YES;
}
您只需将该按钮的框架与所有其他按钮的框架进行比较。 这里有一些示例代码,它应该可能放在你的视图控制器中,因为它需要知道其他按钮。
- (BOOL) button:(UIButton*)button intersectsWithButtons:(NSArray*)moreButtons
{
CGRect buttonFrame = button.frame;
for (UIButton *checkButton in moreButtons) {
if (button != checkButton && CGRectIntersectsRect(buttonFrame, checkButton.frame))
return YES;
}
return NO;
}
我这里 有一个错误,如果(按钮!= checkButton && CGRectIntersectsRect(buttonFrame,checkButton.frame) i'trying当使用checkButton.frame; – Arthur 2013-05-01 13:11:23
什么样的错误? – aLevelOfIndirection 2013-05-01 17:27:51
我已经更新了我的答案有一个更通用的解决方案,如果你要检查它 – 2013-05-01 13:23:51