【问题标题】:Manually passing touches Began to a newly created instance手动传递触摸开始到新创建的实例
【发布时间】:2013-08-20 05:05:38
【问题描述】:

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

有什么办法吗?

【问题讨论】:

  • 我尝试了 CodenameLambda1 解决方案。 5分钟搞定! :)

标签: iphone ios xcode


【解决方案1】:

您必须派生 UIView 的子类,它将充当所有新生成的视图的 HolderView。此外,一旦生成了新视图,即使手指没有抬起,新视图也会随着手指移动。

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

@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

【讨论】:

    【解决方案2】:

    我认为当您触摸其他对象时,触摸会在您的末端产生问题,该视图也存在,因此无法在您的可移动对象上识别触摸,因为您需要在 UIView 上使用一个 UIImageview,然后检测触摸然后你就可以实现你想要的输出了

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint imgPop = [touch locationInView:imgPopup];
        if ([imgPopup pointInside:imgPop withEvent:event])
        {
            CGPoint imgReply = [touch locationInView:viewComment];
            if ([viewComment pointInside:imgReply withEvent:event])
            {
    
            } else {
                viewPopup.hidden = TRUE;
            }        
        }
    }
    

    这是我管理此代码的方式,用于关闭触摸视图,但您可以修改并用于您的目的。

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多