处理自定义组件:子类UIView或UIViewController?

我正在做一个UISegmentedControl的自定义实现。 我想创build一个组件,能够接收configuration数据,并从中获得类似于UISegmentedControl的自定义视图。

我开始子类UIView,我可以用这个代码创build一个自定义的UISegmentedControl:

CustomSegment *segment = [[CustomSegment alloc] initWithTitles:[NSArray arrayWithObjects:@"one",@"two",nil]]; [self.window addSubview:segment]; 

但是现在我想改善我的课程,并为它增加一些可定制的参数。 例如,我想添加一个自定义分隔符,定义button字体等…在这里,我怀疑:在UIView子类上工作是更好还是build议我inheritance一个UIViewController,我可以在其中pipe理视图层次结构方法像 – (void)loadView-(void)viewDidLoad

在一个简单的UIView子类中,当我启动自定义init方法时,我立即设置子视图…而使用UIViewController我可以调用自定义的初始化和定义如何我的子视图被build成 – (无效)loadView。

不要使用UIViewController,只要像你一样扩展UIView类,并继续扩展它的function。

请记住保存一个指向你添加的每个子视图的指针(即button),以便以后可以访问它们。

定义自定义setter,例如,更改button标签标题的自定义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方法,但我想告诉你我想说什么。

比方说,例如我需要创build一个UIView类来代表我的应用程序中的“联系人”对象。

这是我会做的:

 @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”将正确的框架和数据设置为标签。 通常,在创build自定义的UITableViewCells的时候,我经常使用它来重用视图。

让我知道如果我混乱。