不要使用UIViewController,只需像你一樣擴展UIView類並繼續擴展它的功能。
請記住保存一個指向您添加的每個子視圖(即按鈕)的指針,以便稍後能夠訪問它們。
定義自定義setter方法,例如,改變按鈕標籤標題定製的setter是:
- (void) setButton1Title:(NSString*)str forState:(UIControlState)state{
//You can add some control here
if ([str length] > 20) return;
[_button1 setTitle:str forState:state]; //_button1 is my reference to the button
}
等。不要直接訪問你的子視圖,而要使用方法。
此外,您可以使用「layoutSubviews」方法來定義您的視圖將如何顯示在您的自定義視圖中。
希望它可以幫助你。
編輯:在你的情況,我沒有,但爲什麼用lauoutSubviews方法我想告訴你什麼,我想說的。
可以說,例如我需要創建一個UIView類來表示我的應用程序中的「Contact」對象。
這是我會做什麼:
@interface ContactView : UIView{
UILabel* _nameLabel;
UILabel* _ageLabel;
Contact* _contact;
}
@property (retain) Contact* contact;
@end
@implementation ContactView
@synthetize contact = _contact;
-(id)initWithContact:(Contact*)c{
self = [super init];
if (self) {
_nameLabel = [[UILabel alloc] init];
_nameLabel.frame = CGRectZero;
[self addSubview:_nameLabel];
[_nameLabel release];
_ageLabel = [[UILabel alloc] init];
_ageLabel.frame = CGRectZero;
[self addSubview:_ageLabel];
[_ageLabel release];
self.contact = c;
}
}
- (void) layoutSubviews{
[super layoutSubviews];
_nameLabel.frame = CGRectMake(0.0f, 0.0f, 200.0f, 25.0f);
_ageLabel.frame = CGRectMake(0.0f, 25.0f, 200.0f, 25.0f);
if (self.contact){
_nameLabel.text = self.contact.name;
_ageLabel.text = self.contact.age;
}else{
_nameLabel.text = @"Unavailable";
_ageLabel.text = @"Unavailable";
}
}
- (void) setContact:(Contact*)c{
self.contact = c;
[self layoutSubviews];
}
@end
時退房「layoutSubiews」如何來設置正確的框架和數據的標籤。 通常,我在創建自定義UITableViewCells時需要重複使用視圖。
讓我知道我是否感到困惑。
也考慮繼承UIControl – Felix 2011-04-14 19:06:22