他們都期待適當不同的是自定義視圖我。如果你只是想要一個單一的視圖這樣的控制(即不是一個更靈活的可配置容器類型控制),它應該是相對較快的容易在Xcode & IB中敲它。我在我的應用中做過類似的事情。有步驟,我將採取如下:
1)創建一個空的NIB文件,並使用的UIView,UIImageView的,UIButton的控制等設計自己的控制有
2)創建一個從UIView的
派生的新ObjC類
3)確保「根」在NIB的UIView對象具有類類型符合ObjC UIView的派生類
4)將IBOutlets & IBAction爲事件處理程序到類及導線上的所有按鈕事件('內觸摸了')添加到IB中的類事件處理程序方法中。
5)添加一個靜態工廠函數給你的類從NIB創建它自己。例如
// Factory method - loads a NavBarView from NavBarView.xib
+ (MyCustomView*) myViewFromNib;
{
MyCustomView* myView = nil;
NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomViewNib" owner:nil options:nil];
// The behavior here changed between SDK 2.0 and 2.1. In 2.1+, loadNibNamed:owner:options: does not
// include an entry in the array for File's Owner. In 2.0, it does. This means that if you're on
// 2.2 or 2.1, you have to grab the object at index 0, but if you're running against SDK 2.0, you
// have to grab the object at index:1.
#ifdef __IPHONE_2_1
myView = (MyCustomView *)[nib objectAtIndex:0];
#else
myView = (MyCustomView *)[nib objectAtIndex:1];
#endif
return myView;
}
6)創建並放置到正常的父視圖:
MyCustomView* myView = [MyCustomView myViewFromNib];
[parentView addSubview:myView];
myView.center = parentView.center;
對於事件處理,我傾向於只創建一個按鈕的事件處理程序,並使用通過ID參數去通過比較IBOutlet成員或UIView標籤來確定按下哪個按鈕。我還經常爲自定義視圖類創建一個委託協議,並通過該按鈕的事件處理程序中的委託進行回調。 例如
MyCustomViewDelegate.h:
@protocol MyCustomViewDelegate
- (void) doStuffForButton1;
// etc
@end
ParentView.m:
myView.delegate = self;
- (void) doStuffForButton1
{
}
MyCustomView.m:
- (IBAction) onButtonPressed:(id)button
{
if (button == self.button1 && delegate)
{
[delegate doStuffForButton1];
}
// or
UIView* view = (UIView*)button;
if (view.tag == 1 && delegate)
{
[delegate doStuffForButton1];
}
}
希望幫助