gpt4 book ai didi

ios - swift 3.0 : Custom CollectionView header button click

转载 作者:行者123 更新时间:2023-11-29 00:18:20 30 4
gpt4 key购买 nike

我制作了一个自定义的 collectionview 单元格。我通过这段代码将它作为 Collection View 的标题:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {

let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCell", for: indexPath) as! GridHeaderCollectionViewCell
cell.pagePluginBtn.tag = 0
cell.tag = 0
cell.nameLabel.text = pageRecord["GroupName"] as? String
cell.pagePluginBtn.addTarget(self, action: #selector(TappedOnPagePluginBtn(sender:)), for: .touchUpInside)
return cell
}
abort()
}

func TappedOnPagePluginBtn(sender:UIButton){

print("in plugin")
}

单元格定义为:

class GridHeaderCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var pagePluginBtn: UIButton!
}

TappedOnPagePluginBtn() 根本没有被调用。有没有办法让collectionView的headerView中的按钮可以点击?

最佳答案

第二种方式(不是第二种,我的更好的版本)来自 ALCameraViewController 的创建者 AlexLittlejohn .

您可以创建一个 UIButton 扩展来添加操作,例如添加目标。

typealias ButtonAction = () -> Void

extension UIButton {

private struct AssociatedKeys {
static var ActionKey = "ActionKey"
}

private class ActionWrapper {
let action: ButtonAction
init(action: @escaping ButtonAction) {
self.action = action
}
}

var action: ButtonAction? {
set(newValue) {
removeTarget(self, action: #selector(performAction), for: .touchUpInside)
var wrapper: ActionWrapper? = nil
if let newValue = newValue {
wrapper = ActionWrapper(action: newValue)
addTarget(self, action: #selector(performAction), for: .touchUpInside)
}

objc_setAssociatedObject(self, &AssociatedKeys.ActionKey, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
guard let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.ActionKey) as? ActionWrapper else {
return nil
}

return wrapper.action
}
}

@objc func performAction() {
guard let action = action else {
return
}

action()
}
}

然后;

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseIdentifier, for: indexPath) as! GridHeaderCollectionViewCell

view.pagePluginBtn.action = {
print("yeah we catch it!")
}

return view
}

关于ios - swift 3.0 : Custom CollectionView header button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744231/

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