从NSArray设置UISegmentedControl的标题

时间:2013-04-23 07:40:54

标签: ios objective-c uisegmentedcontrol

我试图继承UISegmentedControl
我从视图中传递了NSArray,并尝试从UISegmentedControl设置NSArray的标题。
我使用了initWithArray方法,但没有设置数组中的值。

这是我的UISegmentedControl的子类。

WTSegmentedControl.h

@interface WTSegmentedControl : UISegmentedControl {

}
@end

WTSegmentedControl.m

#import "WTSegmentedControl.h"

@implementation WTSegmentedControl

- (id)initWithItems:(NSArray *)items {
    if (self = [super initWithItems:items]) {

    }
    return self;
}

现在从视图中我称之为这种方法。

我连接了这样的插座:

@property (nonatomic,strong) IBOutlet WTSegmentedControl  *control;

- (void)viewDidLoad {
    NSArray *names = [[NSArray alloc] initWithObjects:@"yes", @"no", nil];
    control = [[WTSegmentedControl alloc] initWithItems:names];
}

NSArray正确传递,但titles未设置。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

好,所以你在Interface Builder中或通过代码创建控件!?你不能两者都做。 如果要在代码中创建它,请删除属性中的IBOutlet部分,并在初始化后将控件添加到subView:

// adding the control by code
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *names = [[NSArray alloc] initWithObjects:@"yes", @"no", nil];
    control = [[WTSegmentedControl alloc] initWithItems:names];
    control.frame = CGRectMake(x,z,width,height);
    [self.view addSubview: control];
}

但是如果你想在InterfaceBuilder中创建它,你就不应该重新初始化它。在Interface Builder中设置自定义类,然后只需设置如下标题:

// using Interface Builder
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *names = [[NSArray alloc] initWithObjects:@"yes", @"no", nil];
    [names enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL *stop) {
        [control setTitle:title forSegmentAtIndex:idx];
    }];
}

答案 1 :(得分:0)

如果已正确连接IBOutlet控件,则此时将自动设置控制变量。这是在加载视图时完成的。 这一行:

control = [[WTSegmentedControl alloc] initWithItems:names];

应改为:

[control initWithItems:names];
相关问题