一、定製可重用的 IB 組件 CheckButton
1、建立 Single View Application,勾選“Use Automatic Referencing Counting”和“UseStoryBoards”。
2、建立一個xib,名為 CheckButton.xib 。建立一個 UIControl 子類 CheckButton,作為 xib 的 File'sowner 的 class。
3、在IB 中將 view 的“Use Autolayout”反選。Size 設定為 Freedom。
4、拖入一個 UIButton,設定 Default 圖片和 Selected 圖片分別為 checkbox2.png 和 checkbox.png。
5、將 View 和 Button 分別串連至出口 view 和 button。
6、CheckButton 類實現如下:
// CheckButton.h 檔案
#import <UIKit/UIKit.h>
@interface CheckButton : UIControl{
}
@property(strong,nonatomic)IBOutletUIButton *button;
@property(strong,nonatomic)NSString* title;
@property (strong, nonatomic) IBOutletUIView *view;
@end
// CheckButton.m 檔案
#import "CheckButton.h"
@implementation CheckButton
@synthesize button=button;
-(void)setupView{
[[NSBundlemainBundle] loadNibNamed:@"CheckButton"owner:selfoptions:nil];
[buttonsetFrame:self.bounds];
[buttonaddTarget:selfaction:@selector(doSelect:) forControlEvents:UIControlEventTouchUpInside];
[selfaddSubview:self.view]; //where self.view is IBOutlet connectedwith the actual Xib view I
}
-(id)initWithFrame:(CGRect)frame{
if((self = [superinitWithFrame:frame])){
[selfsetupView];
}
returnself;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if((self = [superinitWithCoder:aDecoder])){
[selfsetupView];
}
returnself;
}
- (void) awakeFromNib
{
[superawakeFromNib];
[selfaddSubview:self.view];
}
- (void)layoutSubviews{
button.frame=self.bounds;
}
-(BOOL)isSelected{
returnbutton.selected;
}
-(void)setSelected:(BOOL)selected{
[buttonsetSelected:selected];
}
-(NSString*)title{
returnbutton.titleLabel.text;
}
-(void)setTitle:(NSString *)title{
// reserve sufficient space for icon.
[buttonsetTitle:[@" "stringByAppendingString:title] forState:UIControlStateNormal];
}
-(void)doSelect:(UIButton*)sender{
[selfsetSelected:!sender.selected];
[selfsendActionsForControlEvents:UIControlEventTouchUpInside];
}
@end
二、在 ViewController 中使用自訂群組件
7、開啟故事板,拖一個 UIView 到 view 中,將 class 改為 CheckButton。
8、將 CheckButton 串連至出口 checkbox。
9、在串連面板,將 CheckButton 的 Touch Up Inside 串連到 IBAction :
- (IBAction)saveSecurity:(id)sender {
NSLog(@"save security button isselected:%d",_checkbox.selected);
}
10、在 ViewController 的 viewDidLoad 方法中修改 checkbox 的標題文本:
_checkbox.title=@"記住密碼";
11、OK,運行程式,大功告成。原始碼在資源中下載。