看板 MacDev 關於我們 聯絡資訊
※ 引述《issuemylove (skill)》之銘言: : 最近想要作一個view,如下 : ┌───────┐ : │ │ : │ UILabel │ : │ │ : │ A │ : │ │ : │ other UIView │ : │ │ : │ │ : └───────┘ : 其中 A view (UIView) 的部分想要動態決定是屬於哪種 view : 例如 A 可能是 UIImageView 或 UITextView 或 UILabel : 我目前的寫法是 定一個 array 裡面存 NSNumber : 也就是說目前 index 在array 第 index 個的時候 : alloc 出對應的 xxx type View : 寫法是 if( index == [NSNumber intValue]) : alloc UIImageView : else if( index == [NSNumber intValue]) : alloc UILabelView : else : .... alloc 其他 type : 然後讓 A = xxx type View. : 可是這樣很蠢啊...Orz : 請問有甚麼好方法可以把 if-else 給拔掉呢? : 謝謝QQ 如果你只是想把alloc簡化成一行 NSString *className = nil; id view = nil; switch(2) { case 1: className = @"UIImageView"; break; case 2: className = @"UILabel"; break; default: className = @"UIView"; break; } if (className) { view = [[NSClassFromString(className) alloc] init]; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.163.107.187
issuemylove:謝謝你的幫助!!QQ 10/18 15:36