手动传递触摸开始到新创建的实例 [英] Manually passing touches Began to a newly created instance

查看:28
本文介绍了手动传递触摸开始到新创建的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在触摸 UIView 时创建一个对象.但我希望新对象无需抬起手指即可移动.我尝试将触摸事件传递给新对象,但它不起作用.

I want an object to be created when I touch an UIView. But I want the new object to be able to moved without the finger having to be raised. I tried passing the touched event to the new object but it doesn't work.

有什么办法吗?

推荐答案

您必须派生 UIView 的子类,它将作为所有新生成的视图的 HolderView.此外,一旦生成新视图,即使手指未抬起,新视图也会随着手指移动.

You'll have to derive a subclass of the UIView, which will serve as a HolderView for all newly generated views. Also, once a new view is generated, the new view will move along with the finger even if its not raised.

以下代码将完成,稍后根据您的需要进行调整:

Following code will do it, tweak it later as per your needs:

@interface HolderView : UIView

@property(nonatomic,retain)UIView *newView;

@end

@implementation HolderView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];

    if (CGRectContainsPoint(self.bounds, touchPoint)) {

        CGRect r = CGRectMake(touchPoint.x-50, touchPoint.y-50, 100, 100);

        self.newView = [[[UIView alloc] initWithFrame:r]autorelease];
        self.newView.backgroundColor= [UIColor cyanColor];
        [self addSubview:self.newView];

    }
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.newView!=nil) {
        UITouch *touch = [touches anyObject];
        CGPoint touchPoint = [touch locationInView:self];
        self.newView.center = touchPoint;
    }
}

@end

这篇关于手动传递触摸开始到新创建的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆