开发者

Better switching logic for table view

开发者 https://www.devze.com 2023-03-28 16:42 出处:网络
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:

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

精彩评论

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

关注公众号