草庐IT

ios - 协议(protocol)功能在 swift 3 中不起作用

coder 2023-09-15 原文

这是一个 cardCollectionView 应用程序,我正在尝试使用长按删除项目并在项目中显示删除按钮。我已经可以删除项目,但我的项目不会重新加载到空位置。我发现问题是因为有一个协议(protocol)功能从不工作。

这是我的协议(protocol):

@objc protocol ActionDelegation:class {

func deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell)
func hideAllDeleteBtn()
func showAllDeleteBtn()    
}

hideAllDeleteBtn()showAllDeleteBtn() 函数运行良好,但是 deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell)函数永远不起作用。

weak var delegation : ActionDelegation!

我在这里尝试 print(),但根本没有在这个函数中运行(在 MyCollectionViewCell 类中)

func animationDidStop(_ theAnimation: CAAnimation!, finished flag: Bool){
    delegation.deleteCell(path, self)
}

这是 ViewController 类

我在我的一个函数中做了 cell.delegation = self

在我点击删除按钮后,它应该可以正常工作了,

func deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell){            print("1")
    myCollectionView.performBatchUpdates({ () -> Void in
        print("2")
        self.cellArray.removeObject(at: indexPath.row)
        self.myCollectionView.deleteItems(at: [indexPath])
        print("3")
    }, completion: {(flag:Bool) in
        print("4")
        self.myCollectionView.reloadData()
        print("5")   
    })
}

是的...这个功能永远不会工作,如果这是功能工作那么空的地方不应该是空的。 仅供引用,其他两个协议(protocol)功能都在工作,为什么只有这个不能?

编辑

这是动画部分,它在扩展 NSObject 的 Animation 类中

 class Animation: NSObject {  

   func fadeAnimation(view:UIView){
    let animation = CATransition() 
    animation.delegate = view as? CAAnimationDelegate 
    animation.duration = 0.5 
    view.layer.add(animation, forKey: nil) 
    view.isHidden = true 
}}

它将调用 MyCollectionViewCell 如下所示(在 MyCollectionViewCell 中)

let animation = Animation()

func setAnimation(){

    animation.fadeAnimation(view: self)
}

当我删除项目时,它可以删除并带有淡入淡出的动画

最佳答案

animationDidStop(_:finished:)未被调用,因为您已指定第一个参数是可选的,但事实并非如此。

顺便说一下,如果您指定 MyCollectionViewCell 符合 CAAnimationDelegate (例如,在扩展中,如下所示),编译器会就此问题警告您:

应该是:

extension MyCollectionViewCell: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        ...
    }
}

将来,我可能会建议使用基于 block 的动画来简化与动画有关的任何委托(delegate)相关问题。

protocol ActionDelegate: class {
    func deleteCell(_ cell: UICollectionViewCell)
    func hideAllDeleteBtn()
    func showAllDeleteBtn()
}

class MyCollectionViewCell: UICollectionViewCell {
    weak var delegate: ActionDelegate?

    func fadeAndDelete() {
        UIView.animate(withDuration: 0.5, animations: {
            self.alpha = 0
        }, completion: { _ in
            self.delegate?.deleteCell(self)
        })
    }
}

请注意,我简化了 deleteCell(_:) 委托(delegate)方法,因为您不应该保存 IndexPath,而是及时计算它:

extension ViewController: ActionDelegate {
    func deleteCell(_ cell: UICollectionViewCell) {
        guard let indexPath = myCollectionView.indexPath(for: cell) else { return }

        cellArray.removeObject(at: indexPath.row)   // I might suggest making `cellArray` a Swift array rather than a `NSMutableArray`
        myCollectionView.deleteItems(at: [indexPath])
    }

    func hideAllDeleteBtn() { ... }

    func showAllDeleteBtn() { ... }
}

关于ios - 协议(protocol)功能在 swift 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44996860/

有关ios - 协议(protocol)功能在 swift 3 中不起作用的更多相关文章

  1. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  2. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  6. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  7. CAN协议的学习与理解 - 2

    最近在学习CAN,记录一下,也供大家参考交流。推荐几个我觉得很好的CAN学习,本文也是在看了他们的好文之后做的笔记首先是瑞萨的CAN入门,真的通透;秀!靠这篇我竟然2天理解了CAN协议!实战STM32F4CAN!原文链接:https://blog.csdn.net/XiaoXiaoPengBo/article/details/116206252CAN详解(小白教程)原文链接:https://blog.csdn.net/xwwwj/article/details/105372234一篇易懂的CAN通讯协议指南1一篇易懂的CAN通讯协议指南1-知乎(zhihu.com)视频推荐CAN总线个人知识总

  8. ruby-on-rails - "assigns"在 Ruby on Rails 中有什么作用? - 2

    我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o

  9. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  10. ruby-on-rails - rails 功能测试 - 2

    在Rails自动生成的功能测试(test/functional/products_controller_test.rb)中,我看到以下代码:classProductsControllerTest我的问题是:方法调用products()在哪里/如何定义?products(:one)到底是什么意思?看代码,大概意思是“创建一个产品”,但是它是如何工作的呢?注意我是Ruby/Rails的新手,如果这些是微不足道的问题,我深表歉意。 最佳答案 如果您查看test/fixtures文件夹,您会看到一个products.yml文件。这是在您创建

随机推荐