【发布时间】:2016-07-17 23:53:55
【问题描述】:
我正在学习 BigNerdRanch iOS 编程。我目前正在处理第 11 章(继承 UITableViewCell)中的铜牌挑战
挑战:
更新 ItemCell 以在值小于 50 时以绿色显示 valueInDollars,如果值大于或等于 50 则以红色显示。
我的解决办法是:
cell.valueLabel.textColor = item.valueInDollars < 50 ? UIColor.redColor() : UIColor.greenColor()
现在我将这个逻辑放在我的 ItemsViewController (UITableViewController)、tableView(cellForRowAtIndexPath) 函数中。
// Get a new or recycled cell
let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! ItemCell
// Update the labels for the new preferred text size
cell.updateLabels()
if (itemStore.allItems.count == indexPath.row) {
cell.nameLabel.text = "No more items!"
cell.serialNumberLabel.text = ""
cell.valueLabel.text = ""
} else {
// Set the test on the cell with the description of the item
// that is at the nth index of items, where n = row this cell
// will appear in on the tableview
let item = itemStore.allItems[indexPath.row]
cell.nameLabel.text = item.name
cell.serialNumberLabel.text = item.serialNumber
cell.valueLabel.text = "$\(item.valueInDollars)"
cell.valueLabel.textColor = item.valueInDollars < 50 ? UIColor.redColor() : UIColor.greenColor()
}
return cell
将逻辑放置在控制器或 ItemCell 类中是更好的做法吗?
class ItemCell: UITableViewCell {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var serialNumberLabel: UILabel!
@IBOutlet var valueLabel: UILabel!
func updateLabels() {
let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
nameLabel.font = bodyFont
valueLabel.font = bodyFont
let caption1Font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
serialNumberLabel.font = caption1Font
}
func updateValueTextColor(forValue value: Int) {
valueLabel.textColor = value < 50 ? UIColor.redColor() : UIColor.greenColor()
}
}
在上一章中,他们谈到了依赖倒置原则和设计模式,如 MVC 和依赖注入。这是这些概念之一的应用吗?通过注入依赖,他们提到您不希望对象假定他们需要使用哪些较低级别的对象。我是否将这种设计模式与模型视图控制器混淆了,其中单元不应该对内容的逻辑一无所知?我正试图围绕所有这些概念和模式进行思考,并能够识别它们。
【问题讨论】:
标签: ios swift design-patterns model-view-controller dependency-injection