使用Interface Builder检测UIView上的触摸

blu*_*yd8 2 iphone cocoa-touch uiview

如何仅使用代码检测a UIviewController中的触摸UIView(没有Interface Builder)?

我找到了touchesBegan方法,但它永远不会被调用.我没有初始化有关此方法的任何其他内容.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
Run Code Online (Sandbox Code Playgroud)

mad*_*ik3 6

#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
Run Code Online (Sandbox Code Playgroud)

  • 该属性应使用"assign"而不保留.设置代表TouchView*tv = ....; tv.delegate = self; ... (2认同)