OGeek|极客世界-中国程序员成长平台

标题: objective-c - 处理自定义组件 : subclass UIView or UIViewController? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:06
标题: objective-c - 处理自定义组件 : subclass UIView or UIViewController?

我正在开发 UISegmentedControl 的自定义实现。 我想创建一个能够接收配置数据并从中获得类似于 UISegmentedControl 的自定义 View 的组件。

我开始继承 UIView,我可以使用以下代码创建自定义 UISegmentedControl:

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

但现在我想改进我的类(class)并为其添加更多可自定义的参数。 例如我想添加一个自定义分隔符,定义按钮字体等等......我的疑问是: 在 UIView 子类上工作是否更好,或者您建议我将 UIViewController 子类化,我可以在其中管理 View 层次结构,如 -(void)loadView-(void)viewDidLoad ?

在一个简单的 UIView 子类中,当我启动自定义 init 方法时,我会立即设置 subview ...在使用 UIViewController 时,我可以调用自定义 init 并定义如何将我的 subview 构建到 -(void)loadView 中。



Best Answer-推荐答案


不要使用 UIViewController,只需像您一样扩展 UIView 类并继续扩展其功能。

请记住保存指向您添加的每个 subview (即按钮)的指针,以便以后能够访问它们。

定义自定义 setter ,例如,用于更改按钮标签标题的自定义 setter 将是:

- (void) setButton1TitleNSString*)str forStateUIControlState)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)initWithContactContact*)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) setContactContact*)c{
    self.contact = c;
    [self layoutSubviews];
}

@end

查看如何使用“layoutSubiews”为标签设置正确的框架和数据。 通常,在创建必须重用 View 的自定义 UITableViewCells 时,我经常使用它。

如果我感到困惑,请告诉我。

关于objective-c - 处理自定义组件 : subclass UIView or UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668221/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4