我希望在触摸 UIView 时创建一个对象。但我希望新对象能够移动而不必抬起手指。我尝试将触摸事件传递给新对象,但它不起作用。
有什么办法吗?
您必须派生 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
我认为当您触摸其他对象时,触摸会在您的末端产生问题,因此视图也存在,因此无法在可移动对象上识别触摸,因为您需要在 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;
}
}
}
这就是我管理此代码的方式,用于关闭触摸视图,但您可以修改并用于您的目的。