开发者

Better switching logic for table view

Im my table view, I want to switch the accessory from a checkmark, to not having a checkmark (and back again) - I currently do it like this:

if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    cell.accessoryType = UITableViewCellAccessoryNone;
}
else {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

Now I know there is a better way of wri开发者_C百科ting this, any suggestions?


The only problem I see with what you've got now is that it relies on the cell to save state. The decision about whether to give a cell a check or not should probably be based not on the cell but on the data that's being displayed in the cell, like:

if (vehicle.selected) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

If you want to make that a little more cryptic, you could:

cell.accessoryType = vehicle.selected ? UITableViewCellAccessoryCheckmark
                                      : UITableViewCellAccessoryNone;

Some folks like that notation, others hate it. Check your local coding standards document to find out whether such code is acceptable before using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜