【发布时间】:2018-06-20 19:39:01
【问题描述】:
我正在使用集合视图来显示大约 30 个不同的单元格。每个单元格代表一项冬季运动。这些单元格由静态数据模型填充,并在每次应用更新时更新(无数据库)。
由于我总是添加到运动列表中,我想在添加的最新运动上显示“新”徽章。当用户点击该特定运动时,“NEW”徽章会消失并通过 UserDefaults 持续存在。截图如下:
我的进度如下。我只是坚持坚持“新”属性,所以一旦点击“新”运动,布尔值就会变为 false 并在 UserDefaults 中更新。
模型。我将在此处更新新标志。如果为真,它将显示徽章(最终将取消隐藏图像视图。
struct WinterModel {
let sportName: String
var new: Bool
}
struct WinterData {
static func allSports() -> [WinterModel] {
return [
WinterModel(sportName: "Luge", new: true),
WinterModel(sportName: "Curling", new: false),
WinterModel(sportName: "Skeleton", new: false),
WinterModel(sportName: "Speed Skating", new: false),
WinterModel(sportName: "Bobsleigh", new: false)
// 30+ more
]
}
}
主 VC。 填充集合视图。
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var winter = WinterData.allSports()
@IBOutlet weak var sportCollectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return winter.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath as IndexPath) as! WinterSportCell
let sport = winter[indexPath.item]
cell.sport = sport
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
sportCollectionView.dataSource = self
sportCollectionView.delegate = self
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Cell was changed... Change data model to false?
}
}
最后,UICollectionViewCell
class WinterSportCell: UICollectionViewCell {
@IBOutlet weak var sportNameLabel: UILabel!
@IBOutlet weak var newOutlet: UILabel!
var sport: WinterModel! {
didSet {
self.updateUI()
}
}
func updateUI() {
sportNameLabel.text = sport.sportName
if sport.new {
newOutlet.isHidden = false
} else {
newOutlet.isHidden = true
}
}
}
如何配置 UserDefaults,以便在用户点击该单元格时数据模型的“新”属性更新为 false?
【问题讨论】:
标签: swift uicollectionview nsuserdefaults uicollectionviewcell