繁体   English   中英

使用Interface Builder检测UIView上的触摸

[英]Detect touch on UIView with Interface Builder

如何仅使用代码(没有Interface Builder)在UIViewUIviewController检测触摸?

我找到了touchesBegan方法,但是它从未被调用过。 关于此方法,我没有初始化其他任何事情。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
#import "TouchView.h"


//TouchView.h

#import <Foundation/Foundation.h>
#import "TouchViewDelegate.h"

@interface TouchView : UIView {
    id <TouchViewDelegate>  delegate;
}
@property (retain) id delegate;
@end

//TouchView.m

@implementation TouchView
@synthesize delegate;

-(id) initWithFrame:(CGRect)frame
{
    self.userInteractionEnabled = YES;
    return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
    self.userInteractionEnabled = YES;
    return self;
}
-(void) awakeFromNib
{
    self.userInteractionEnabled = YES;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [delegate touchDown:self];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [delegate touchUp:self];
}
@end

//TouchViewDelegate.h
#import <UIKit/UIKit.h>


@protocol TouchViewDelegate
-(void) touchDown:(id) sender;
-(void) touchUp:(id)sender;
@end

我将阅读《 iPhone应用程序编程指南》的“ 触摸事件”部分

UIViewControllerUIView都是UIResponders ,负责处理事件。

要处理事件,您需要重写touch *方法以执行所需的操作。 要了解发生了哪种触摸事件,请查看UIEvent

在你的init方法中:

self.userInteractionEnabled = YES;

对madmik3的更正,

您在initWithFrame中缺少超级调用。

-(id) initWithFrame:(CGRect)frame {
 if (self = [super initWithFrame:frame]) {
 self.userInteractionEnabled = YES;
 }  return self;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM