做項目封裝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.
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裡把自身的frame也可以