在我的代码中,cell如果它在第一tableView部分中,则将是一种类型,如果不是,则将是另一种类型.
var cell = UITableViewCell()
if indexPath.section == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("UpcomingWorkoutCell", forIndexPath: indexPath) as! MyWorkoutsTableViewCell
cell.nameLabel.text = workout.trainer.name
cell.dateLabel.text = workout.getDateString()
cell.timeLabel.text = workout.getTimeString()
cell.trainerImage.image = workout.image
} else {
cell = tableView.dequeueReusableCellWithIdentifier("PastWorkoutCell", forIndexPath: indexPath) as! PastWorkoutTableViewCell
cell.nameLabel.text = workout.trainer.name
cell.dateLabel.text = workout.getDateString()
cell.timeLabel.text = workout.getTimeString()
cell.trainerImage.image = workout.image
cell.ratingControl.rating = workout.rating // Exclusive to PastWorkoutCell
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来写这个?我可以以某种方式摆脱最初的声明作为一个UITableViewCell并通过一行缩短我的代码?
此外,MyWorkoutsTableViewCell和PastWorkoutCell几乎具有相同的所有属性.我可以避免在if语句的每个分支中重复代码来设置所有这些代码吗?现在单元格是UITableViewCell没有任何属性的,所以我似乎无法在两个分支之外进行.
你试试这个吗?
var cell = tableView.dequeueReusableCellWithIdentifier("UpcomingWorkoutCell", forIndexPath: indexPath) as! MyWorkoutsTableViewCell
if indexPath.section != 0 {
cell = tableView.dequeueReusableCellWithIdentifier("PastWorkoutCell", forIndexPath: indexPath) as! PastWorkoutTableViewCell
cell.ratingControl.rating = workout.rating
}
cell.nameLabel.text = workout.trainer.name
cell.dateLabel.text = workout.getDateString()
cell.timeLabel.text = workout.getTimeString()
cell.trainerImage.image = workout.image
Run Code Online (Sandbox Code Playgroud)