1

我写了一些糟糕的代码,但它有效。有没有更好的方法来写这个?_decade.x 是 NSButton。

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;
4

1 回答 1

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 尚不支持IBOutletCollections,因此您需要将_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;
}
于 2013-07-21T13:46:01.247 回答