看看下面的代碼:如何使用點符號內的字符串訪問屬性?
@property (weak, nonatomic) UILabel *l112;
@property (weak, nonatomic) UILabel *l212:
@property (weak, nonatomic) UILabel *l312:
((RBScorecardVC *)self.presentingViewController).l112.text = @"Hello"
((RBScorecardVC *)self.presentingViewController).l212.text = @"Hello"
((RBScorecardVC *)self.presentingViewController).l312.text = @"Hello"
請注意,我怎麼設置我的標籤的所有文本爲「Hello」。必須有一個更有效的方式來做到這一點。我希望能夠以某種方式訪問UIlabels(l112,1212等)的名稱。這有意義嗎?在我的實際應用程序中,我並沒有將所有內容都設置爲「你好」,而是文本是計算的結果。此外,在我的實際應用程序,我有3組以上的標籤設置(有50+)下面是一個使用重複的if語句來sparately訪問每一個的UILabel我的實際代碼:
-(IBAction) submitScore: (id)sender
{
self.stringID = ((RBScorecardVC *)self.presentingViewController).self.giveString;
if (self.stringID isEqualToString:@"l112")
{ ((RBScorecardVC *)self.presentingViewController).l112.text = [[NSString alloc]initWithFormat:@"%d", self.accumulator];} //l112 is the name of my UILabel
else if (self.stringID is EqualToString:@"l212")
{ ((RBScorecardVC *)self.presentingViewController).l212.text = [[NSString alloc]initWithFormat:@"%d", self.accumulator];} //l212 is the name of my UILabel
}
我希望能夠更有效地做到這一點是這樣的:
-(IBAction) submitScore: (id)sender
self.stringID = ((RBScorecardVC *)self.presentingViewController).self.giveString;
((RBScorecardVC *)self.presentingViewController).[UILabel withTitle:@"%@",stringID].text = [[NSString alloc]initWithFormat:@"%d", self.accumulator];}
通知我[的UILabel withTitle:@ 「%@」 的StringID]點符號中使用的部分。我知道這不起作用,但我想知道如何正確地寫這個,所以stringID可以用來訪問我需要的UILabel的名稱?
什麼是'+ [UILabel withTitle:]'? – 2013-02-07 23:01:07
你應該使用一個NSArray,並有一個使用該數組的搜索方法。用戶界面元素NSArray可以通過'IBOutletCollection'設置。 – Vinzzz