命名一些NSButtons

时间:2013-07-21 13:43:12

标签: cocoa nsbutton

我写了一些可怕的代码,但它确实有效。有没有更好的方法来写这个? _decade.x是NSButtons。

int baseDecade = 1940;
NSString *title;
int currentDecade = 0;

- (IBAction)nameDecade:(id)sender {

    currentDecade = baseDecade;
    title = [NSString stringWithFormat: @"%ld", (long)currentDecade];
    _decade1.stringValue = title;

    currentDecade = currentDecade +10;
    title = [NSString stringWithFormat: @"%ld", (long)currentDecade];
    _decade2.stringValue = title;

    currentDecade = currentDecade +10;
    title = [NSString stringWithFormat: @"%ld", (long)currentDecade];
    _decade3.stringValue = title;

1 个答案:

答案 0 :(得分:1)

在iOS中,您可以将按钮放在界面构建器中的单个IBOutletCollection中,或者如果您通过代码创建按钮,则可以放在NSArray中。有了这个插座集合/数组,您可以使用循环通过集合中的索引引用_decadeN

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *decadeButtons;
...
for (int i = 0 ; i != decadeButtons.count ; i++) {
    UIButton * decade = decadeButtons[i];
    NSString *title = [NSString stringWithFormat: @"%ld", (long)(baseDecade+10*i)];
    decade.stringValue = title;
}

修改 OSX does not support IBOutletCollections yet,因此您需要将_decadeN按钮置于数组中:

// I am using the new array literal syntax; using arrayWithObjects will work too.
NSArray *decadeButtons = @[_decade1, _decade2, _decade3];
// Use the same loop as above:
for (int i = 0 ; i != decadeButtons.count ; i++) {
    UIButton * decade = decadeButtons[i];
    NSString *title = [NSString stringWithFormat: @"%ld", (long)(baseDecade+10*i)];
    decade.stringValue = title;
}