我正在研究 UISegmentedControl 的自定义实现。 我想创建一个能够接收配置数据并从中获取类似于 UISegmentedControl 的自定义 View 的组件。
我开始子类化 UIView,我可以使用以下代码创建自定义 UISegmentedControl:
CustomSegment *segment = [[CustomSegment alloc]
initWithTitles:[NSArray arrayWithObjects:@"one",@"two",nil]];
[self.window addSubview:segment];
但现在我想改进我的类并向其添加一些更多可自定义的参数。
例如,我想添加自定义分隔符,定义按钮字体等等......这是我的疑问:
是在 UIView 子类上工作更好还是建议我对 UIViewController 进行子类化,我可以在其中管理 View 层次结构,如 - (void)loadView
和-(void)viewDidLoad
?
在一个简单的 UIView 子类中,当我启动自定义 init 方法时,我立即设置 subview ...在使用 UIViewController 时,我可以调用自定义 init 并定义如何将我的 subview 构建到 -(void)loadView 中。
最佳答案
不要使用 UIViewController,只需像您一样扩展 UIView 类并继续扩展其功能。
请记住保存指向您添加的每个 subview (即按钮)的指针,以便以后能够访问它们。
定义自定义 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
}
等等。不要提供对 subview 的直接访问,而是使用方法。
此外,您还可以使用“layoutSubviews”方法来定义 View 在自定义 View 中的显示方式。
希望对您有帮助。
编辑:就您而言,我不明白为什么使用 lauoutSubviews 方法,但我想向您展示我想说的内容。
假设我需要创建一个 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”为标签设置正确的框架和数据。 通常,我在创建自定义 UITableViewCells 时经常使用它,您必须重用 View 。
如果我感到困惑,请告诉我。
关于objective-c - 处理自定义组件 : subclass UIView or UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668221/