关于UIButton嵌入到UIView点击无反应问题的解决方法和delegate的简单用法示例(转载)

时间:2022-06-02 07:50:03

做项目封装UIView的时候碰到的问题,没想到有个哥们儿还写成博客,特此收藏!

问题是这样的,几个界面用到同一个自定义返回按钮,于是就想着把这个按钮单独封装起来,添加一个UIView类,在里面自定义UIButton,使用delegate来实现点击事件

//UIView类头文件XZXTopView.h

#import <UIKit/UIKit.h>

@protocol BtnDelegate <NSObject>  //定义一个delegate

- (void)dismissViewController;    //声明一个delegate方法

@end

@interface XZXTopView : UIView{

id <BtnDelegate> delegate;        //声明delegate变量

}

@property (nonatomic, strong) id <BtnDelegate> delegate;   //声明delegate属性

@end

//UIView类XZXTopView.m

#import "XZXTopView.h"

@implementation XZXTopView

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

// Initialization code

    //自定义一个UIButton

UIButton *button=[UIButtonbuttonWithType:UIButtonTypeCustom];

UIImage *image = [UIImage imageNamed:@"b_back"];

[button setImage:image forState:UIControlStateNormal];

[button setFrame:CGRectMake(5., 7., image.size.width, image.size.height)];

[button addTarget:selfaction:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

[self addSubview:button];

}

return self;

}

- (void)buttonClicked:(UIButton *)sender{

[delegate dismissViewController];  //点击按钮执行此delegate方法

}

//UIViewController类头文件XZXHelpViewController.h

#import <UIKit/UIKit.h>

#import "XZXTopView.h"

@interface XZXHelpViewController : UIViewController<BtnDelegate>  //这里

@end

//UIViewController类 XZXHelpViewController.m文件

#import "XZXHelpViewController.h"

@interfaceXZXHelpViewController ()

@end

@implementation XZXHelpViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

returnself;

}

- (void)viewDidLoad

{

[superviewDidLoad];

// Do any additional setup after loading the view from its nib.

XZXTopView *topView = [[XZXTopView alloc] init];   //错误的初始化

topView.delegate = self;    //定义XZXTopView的时候指定其代理为自身

[self.view addSubview:topView];

}

- (void)didReceiveMemoryWarning

{

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

//点击button后的具体执行方法

- (void)dismissViewController

{

[selfdismissViewControllerAnimated:YES completion:NULL];

}

@end

代理简单的用法就是这样

上述代码编译执行后,按钮正常显示,但点击没有反应,这是为什么呢?

受惯性思维影响,认为既然能显示,就点击的到,实际上按钮并没有被真正点击到,那是因为我们并没有设置UIButton的上一层UIView类的frame,即

XZXTopView *topView = [[XZXTopView alloc] init]; 这样的初始化是错误的

这样初始化后topView的frame是默认的(0.0,0.0,0.0,0.0);使得button并没有被点击到

正确的初始化方法:

XZXTopView *topView = [[XZXTopView alloc] initWithFrame:CGRectMake(0.0,0.0,320,50)]; //frame自己设置,比button大就可以了

或者在XZXTopView里把自身的frame也可以

转自:http://www.haogongju.net/art/2043183

iOS开发