gpt4 book ai didi

cocoa - 命名多个 NSButton

转载 作者:行者123 更新时间:2023-12-03 17:12:33 26 4
gpt4 key购买 nike

我写了一些糟糕的代码,但它有效。有更好的方法来写这个吗? _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;

最佳答案

在 iOS 中,您可以将按钮放在一个 IBOutletCollection 中在界面生成器中,或者在 NSArray 中(如果您通过代码创建按钮)。有了该 socket 集合/数组,您可以使用循环通过集合中的索引来引用 _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;
}

关于cocoa - 命名多个 NSButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com