摘要
这个解决方案让我们你锁定某些单元格的背景颜色,其余由系统行为的控制。
基于mientus' answer,我创建了一个解决方案,它可以让你指定哪些意见应保持其背景颜色。
这仍然允许其他单元格子视图在突出显示/选择时删除其背景,并且是在我们的案例中工作的唯一解决方案(需要永久背景的两个视图)。
我使用的面向协议的方法,用含有视图锁定列表中,并运行一个闭合,同时保持颜色的BackgroundLockable
协议:
protocol BackgroundLockable {
var lockedBackgroundViews: [UIView] { get }
func performActionWithLockedViews(_ action: @escaping() -> Void)
}
extension BackgroundLockable {
func performActionWithLockedViews(_ action: @escaping() -> Void) {
let lockedViewToColorMap = lockedBackgroundViews.reduce([:]) { (partialResult, view) -> [UIView: UIColor?] in
var mutableResult = partialResult
mutableResult[view] = view.backgroundColor
return mutableResult
}
action()
lockedViewToColorMap.forEach { (view: UIView, color: UIColor?) in
view.backgroundColor = color
}
}
}
然后我具有UITableViewCell
一个子类,其覆盖突出显示和选择奔波调用默认(超)行为协议的终止:
class LockableBackgroundTableViewCell: UITableViewCell, BackgroundLockable {
var lockedBackgroundViews: [UIView] {
return []
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
performActionWithLockedViews {
super.setHighlighted(highlighted, animated: animated)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
performActionWithLockedViews {
super.setSelected(selected, animated: animated)
}
}
}
现在我只需要继承LockableBackgroundTableViewCell
或使用BackgroundLockable
原在一个单元格类中添加锁定行为,以便轻松添加到某些单元格中
class SomeCell: LockableBackgroundTableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var button: UIButton!
override var lockedBackgroundViews: [UIView] {
return [label, icon]
}
}
还有哪些其他的界面元素的视图中,即得到由小区选择颜色覆盖? – hennes 2011-03-07 17:48:53
目前这只是一个图像。这是为了使图像看起来像一张照片。稍后,我还会在那里添加一个标签。 – P5ycH0 2011-03-07 18:21:20