您的位置:首页 > 产品设计 > UI/UE

原创:关于UIButton嵌入到UIView点击无反应问题的解决方法和delegate的简单用法示例

2013-05-25 11:42 981 查看
最近做项目,几个界面用到同一个自定义返回按钮,于是就想着把这个按钮单独封装起来,添加一个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:YEScompletion: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的frame就可以了

或者在XZXTopView里把自身的frame固定一下也可以。

OK, 就这样一个小小的错误整了一个下午,虽然花了很多时间解决了这样一个小问题,但也学会了不少东西,纪念一下!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐