作者PurGle (ObjC)
标题Re: [问题] 多重型态处理的方法
时间Fri Oct 18 15:21:23 2013
※ 引述《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
1F:推 issuemylove:谢谢你的帮助!!QQ 10/18 15:36