ios 创建自定义UIView作为控件来使用
不想继承 UIViewController,总感觉中间多了一层,用起来始终不够畅快。直接继承 UIView,自定义一个 View 来当作一个类似于 UIButton 的控件来用岂不美哉?
Bogatyr 仁兄给我们提供了一个非常好用的实例,完全按照他的方法做即可!
现在摘录过来
MyView.h
@interface MyView : UIView { UIView *view; UILabel *l; } @property (nonatomic, retain) IBOutlet UIView *view; @property (nonatomic, retain) IBOutlet UILabel *l;
MyView.m
#import "MyView.h" @implementation MyView @synthesize l, view; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code. // [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil]; [self addSubview:self.view]; } return self; } - (void) awakeFromNib { [super awakeFromNib]; [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil]; [self addSubview:self.view]; } - (void) dealloc { [l release]; [view release]; [super dealloc]; }
MyView.xib
然后在其他的 View 中插入一个UIView并把类型改为 MyView 即可