新收藏视图列表单元的问题是我无法将操作处理程序添加到自定义附件视图。
我一直在尝试执行以下操作:
protocol TappableStar: class {
func onStarTapped(_ cell: UICollectionViewCell)
}
class TranslationListCell: UICollectionViewListCell {
let starButton: UIButton = {
let starButton = UIButton()
let starImage = UIImage(systemName: "star")!.withRenderingMode(.alwaysTemplate)
starButton.setImage(starImage, for: .normal)
starButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
starButton.addTarget(self, action: #selector(starButtonPressed(_:)), for: .touchUpInside)
starButton.tintColor = .systemOrange
return starButton
}()
var translation: TranslationModel?
weak var link: TappableStar?
override init(frame: CGRect) {
super.init(frame: frame)
accessories = [.customView(configuration: .init(customView: starButton, placement: .trailing(displayed: .always)))]
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func starButtonPressed(_ sender: UIButton) {
link?.onStarTapped(self)
}
override func updateConfiguration(using state: UICellConfigurationState) {
// Create new configuration object and update it base on state
var newConfiguration = TranslationContentConfiguration().updated(for: state)
// Update any configuration parameters related to data item
newConfiguration.inputText = translation?.inputText
newConfiguration.outputText = translation?.outputText
contentConfiguration = newConfiguration
}
}
我将UICollectionViewListCell子类化,使用目标动作处理程序创建一个按钮并将其添加到附件数组。我也有自己的单元配置实现。
现在,我创建了一个协议,在其中我将动作处理委托给我的视图控制器(我还实现了新的单元格注册API并设置了cell.link = self
)。
我的问题是,starButtonPressed
尽管此附件视图是响应性的,但我的附件按钮没有调用(突出显示时它会更改颜色)。
我的想法是,使用自定义附件实现动作处理的方式可能有问题,但是关于此新api的信息似乎很少。
而且,在预定义的附件之间进行选择时,其中一些附件具有actionHandler
UICellAccessory.ActionHandler类型的闭包,但我似乎不了解如何正确实现。
任何想法将不胜感激。
从iOS 14开始,我们可以使用主要操作来初始化UIButton和其他UIControl。它变得类似于本地附件的处理程序。这样,我们可以使用我们想要的任何参数化方法。而且参数化很重要,因为通常我们要对特定单元格进行一些操作。#selector不能进行参数设置,因此我们无法将任何有关要更新单元格的信息传递给方法。但是此解决方案仅适用于iOS 14+。
创建UIAction:
let favoriteAction = UIAction(image: UIImage(systemName: "star"),
handler: { [weak self] _ in
guard let self = self else { return }
self.handleFavoriteAction(for: your_Entity)
})
创建UIButton:
let favoriteButton = UIButton(primaryAction: favoriteAction)
创建配件:
let favoriteAccessory = UICellAccessory.CustomViewConfiguration(customView: favoriteButton,
placement: .leading(displayed: .whenEditing ))
使用
cell.accessories = [.customView(configuration: favoriteAccessory)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句