在iOS中优化条件



如何优化tableview cell color的if else条件

public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath){
    var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell;
    if (cell == null)
        cell = new TableCell ();
        cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
    if (indexPath.Row % 2 == 0) {
            cell.BackgroundColor = UIColor.White;
        }   else {
            cell.BackgroundColor = UIColor.LightGray;
    }}

这里没有什么可以优化的了。我唯一要改变的是最后一个if -我将用条件表达式替换它:

public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath){
    var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell;
    if (cell == null) {
        cell = new TableCell ();
    }
    cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
    cell.BackgroundColor = (indexPath.Row % 2 == 0) ? UIColor.White : UIColor.LightGray;
}

这是个人偏好的问题,不过:您的if语句有两个赋值也是完全可读的。

也可以使用??创建单元格:

var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell ?? new TableCell();

从外观上看,这也可能是一个轻微的改进,因为附件似乎是一个静态类型,不需要每次都分配:

var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell 
    ?? new TableCell() { Accessory = UITableViewCellAccessory.DisclosureIndicator };

最新更新