gpt4 book ai didi

ios - iOS 14 中的 UICollectionViewListCell 和自定义单元格附件

转载 作者:行者123 更新时间:2023-12-05 00:55:32 26 4
gpt4 key购买 nike

我对新 Collection View 列表单元的问题是我无法将操作处理程序添加到自定义附件 View 。

我一直在尝试做以下事情:

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,创建了一个带有目标操作处理程序的按钮并将其添加到 accessories 数组中。我也有自己的单元配置实现。

现在,我创建了一个协议(protocol),将操作处理委托(delegate)给我的 View Controller (我还实现了新的单元注册 API 并设置 cell.link = self)。

我的问题是我的附件按钮没有调用 starButtonPressed 虽然这个附件 View 是响应式的(突出显示时它会改变颜色)。

我的想法是,我使用自定义附件实现 Action 处理的方式可能有问题,但关于这个新 api 的信息似乎很少甚至没有。

此外,在预定义附件之间进行选择时,其中一些具有 UICellAccessory.ActionHandler 类型的 actionHandler 闭包,但我似乎不明白如何正确实现它。

任何想法都将不胜感激。

最佳答案

iOS 14,使用 UIActions

从 iOS 14 开始,我们可以使用主要操作初始化 UIButton 和其他 UIControl。它变得类似于原生配件的处理程序。有了这个,我们可以使用我们想要的任何参数化方法。参数化很重要,因为通常我们想对特定的单元格做一些 Action 。 #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)]

关于ios - iOS 14 中的 UICollectionViewListCell 和自定义单元格附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64177711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com