簡體   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