将 NSDictionary 中的数组读入 UITableViewCell 子视图
我正在尝试将下面的 plist 字典读入 UITableView 的单元格中。我想为 ArrayKey 表示的数组中包含的每个字符串创建一个子视图,例如:
Row1: | myString1 |
Row2: | myString2 || myString3 |
我使用快速枚举来读取字典,但我只能成功读取每个数组中的第一个字符串:
CGFloat constant = 0;
for (NSArray key in [dictionary objectForKey:@"ArrayKey"]) {
UILabel *label = (UILabel *)cell;
label.text = (NSString *)key;
label.frame = CGRectMake(0 + constant, 0, 30, 30);
constant = 20 + CGRectGetMaxX(label.frame);
}
我缺少子视图部分。我很困惑为什么如果我添加快速枚举的 NSLog,输出将显示数组中的所有字符串,但我只能显示第一个(即 myString1 在一行中,myString2 在第二行中,没有 myString3)。
<dict>
<key>TitleKey</key>
<string>myTitle1</string>
<key>ArrayKey</key>
<array>
<string>myString1</string>
</array>
</dict>
<dict>
<key>TitleKey</key>
<string>myTitle2</string>
<key>ArrayKey</key>
<array>
<string>myString2</string>
<string>myString3</string>
</array>
</dict>
I am attempting to read the plist dictionary below into cells of a UITableView. I want to create a subview for each of the strings contained in the array denoted by the ArrayKey like:
Row1: | myString1 |
Row2: | myString2 || myString3 |
I've used fast enumeration to read the dictionary, but I can only successfully read the first string in each array:
CGFloat constant = 0;
for (NSArray key in [dictionary objectForKey:@"ArrayKey"]) {
UILabel *label = (UILabel *)cell;
label.text = (NSString *)key;
label.frame = CGRectMake(0 + constant, 0, 30, 30);
constant = 20 + CGRectGetMaxX(label.frame);
}
I'm missing the subview piece. And I'm puzzled why if I add an NSLog of the fast enumeration, the output will show all strings in the array, but I can only display the first (ie myString1 in one row and myString2 in a second row without myString3).
<dict>
<key>TitleKey</key>
<string>myTitle1</string>
<key>ArrayKey</key>
<array>
<string>myString1</string>
</array>
</dict>
<dict>
<key>TitleKey</key>
<string>myTitle2</string>
<key>ArrayKey</key>
<array>
<string>myString2</string>
<string>myString3</string>
</array>
</dict>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
令人费解的是为什么这段代码能够正常工作。我确信您只发布了部分代码。
UILabel *label = (UILabel *)cell;
将创建一个指向确切位置的指针相同的项目
cell
并覆盖其中的任何内容。dictionary
为nil
则[dictionary
必须导致崩溃。objectForKey:@"ArrayKey"]
id key
应该是NSString *key
以便将其分配给标签.文本
。您至少需要一个
[cell.contentView addSubView:label];
。Mystifying why this code is working at all. I am sure you are posting only partial code.
UILabel *label = (UILabel *)cell;
will create a pointer to exactlythe same item
cell
and overwrite whatever is there.dictionary
isnil
then[dictionary
must cause a crash.objectForKey:@"ArrayKey"]
id key
should beNSString *key
in order to assign it tolabel.text
.You need at least a
[cell.contentView addSubView:label];
.