大家好,
我第一次使用“触摸方法”所以面临某些问题。在我的应用程序中,mainview 中有 2 个子视图。我正在尝试将 uibutton 从一个视图拖放到另一个视图。我正在尝试很多事情,但无法进行拖放。
请帮我。
提前致谢。
My Code :
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint touchPoint = [[touches anyObject] locationInView:self.viewblue];
for (UIButton *iView in self.view.subviews) {
if ([iView isMemberOfClass:[UIButton class]])
{
if (touchPoint.x > iView.frame.origin.x &&
touchPoint.x < iView.frame.origin.x + iView.frame.size.width &&
touchPoint.y > iView.frame.origin.y &&
touchPoint.y < iView.frame.origin.y + iView.frame.size.height)
{
self.btnalpha = iView;
touchOffset = CGPointMake(touchPoint.x - iView.frame.origin.x,
touchPoint.y - iView.frame.origin.y);
homePosition = CGPointMake(iView.frame.origin.x,
iView.frame.origin.y);
[self.viewblue bringSubviewToFront:self.btnalpha];
}
}
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint touchPoint = [[touches anyObject] locationInView:self.viewblue];
CGRect newDragObjectFrame = CGRectMake(touchPoint.x - touchOffset.x,
touchPoint.y - touchOffset.y,
self.btnalpha.frame.size.width,
self.btnalpha.frame.size.height);
self.btnalpha.frame = newDragObjectFrame;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint touchPoint = [[touches anyObject] locationInView:self.viewblue];
if (touchPoint.x > self.vieworange.frame.origin.x &&
touchPoint.x < self.vieworange.frame.origin.x + self.vieworange.frame.size.width &&
touchPoint.y > self.vieworange.frame.origin.y &&
touchPoint.y < self.vieworange.frame.origin.y + self.vieworange.frame.size.height )
self.btnalpha.frame = CGRectMake(self.homePosition.x, self.homePosition.y, self.btnalpha.frame.size.width, self.btnalpha.frame.size.height);
}
- (void) drag
{
str_scramble =@"IH";
for (int i = 0; i < 2; i++)
{
self.btnalpha = [[UIButton alloc] init];
[self.btnalpha setFrame:CGRectMake(i * 50 + 10, 5, 42, 42)];
char letter = [str_scramble characterAtIndex:i];
self.btnalpha.backgroundColor = [UIColor grayColor];
self.btnalpha.titleLabel.font = [UIFont boldSystemFontOfSize:20];
[self.btnalpha setTitle:[NSString stringWithFormat:@"%c", letter] forState:UIControlStateNormal];
[self.btnalpha addTarget:self action:@selector(touchesBegan:withEvent:) forControlEvents:UIControlEventTouchDown];
[self.btnalpha addTarget:self action:@selector(touchesMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
[viewblue addSubview:self.btnalpha];
NSLog(@"string : --> %@", self.btnalpha.titleLabel.text);
}
}