草庐IT

ios - UITableViewCell 子类的行为不像 UITableViewCells

coder 2024-01-30 原文

我的函数接受类型为 (cell: UITableViewCell, item: AnyObject) -> () 的函数作为参数。

我的问题是,当我尝试将具有 UITableViewCell子类 的函数作为参数传递时,出现错误:

无法将类型“(tableCellSubclass, post: Post) -> ()”的值转换为预期的参数类型“(cell: UITableViewCell, item: AnyObject) -> ()”

如何更改类型为 (cell: UITableViewCell, item: AnyObject) -> () 的函数,以便使用 UITableViewCell 的子类的函数符合它?

这里是相关的代码片段。第一个是我要实例化的 ArrayDataSource。

class ArrayDataSource: NSObject, UITableViewDataSource {
    let items: [AnyObject]
    let cellIdentifier: String
    let configureCellBlock: (cell: UITableViewCell, item: AnyObject) -> ()

    init(items: [AnyObject], cellIdentifier: String, configureCellBlock: (cell: UITableViewCell, item: AnyObject) -> ()) {
        self.items = items
        self.cellIdentifier = cellIdentifier
        self.configureCellBlock = configureCellBlock
        super.init()
    }

    func itemAtIndexPath(indexPath: NSIndexPath) -> AnyObject {
        return items[indexPath.row]
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
        let item = self.itemAtIndexPath(indexPath)

        configureCellBlock(cell: cell, item: item)
        return cell
    }
}

这是我从中实例化 ArrayDataSource 的地方,也是我收到错误的地方。

override func viewDidLoad() {

        // ...

        let postsArrayDataSource = ArrayDataSource(items: posts, cellIdentifier: "tableCell", configureCellBlock: configurePostTableViewCell)

        // ...
}

最后,这是我想作为参数传递的函数。

func configurePostTableViewCell(cell: postTableCell, post: Post) {
        //sets up formatted string for last confirmed
        let lastConfirmed = dateSimplifier(post.confirmed)
        var boldLastConfirmed = NSMutableAttributedString()
        boldLastConfirmed = NSMutableAttributedString(string: "last confirmed: \(lastConfirmed)", attributes: [NSFontAttributeName:UIFont(name: "AvenirNext-Italic", size: 15.0)!])
        boldLastConfirmed.addAttribute(NSFontAttributeName, value: UIFont(name: "AvenirNext-DemiBoldItalic", size: 15.0)!, range: NSRange(location: 16, length: lastConfirmed.characters.count))

        //sets up formatted string for posted date
        let posted = dateSimplifier(post.posted)
        var boldPosted = NSMutableAttributedString()
        boldPosted = NSMutableAttributedString(string: "posted: \(posted)", attributes: [NSFontAttributeName:UIFont(name: "AvenirNext-Italic", size: 15.0)!])
        boldPosted.addAttribute(NSFontAttributeName, value: UIFont(name: "AvenirNext-DemiBoldItalic", size: 15.0)!, range: NSRange(location: 8, length: posted.characters.count))

        //sets up formatted string for title & type
        let title = post.title
        let type = post.type
        var boldTitle = NSMutableAttributedString()
        boldTitle = NSMutableAttributedString(string: "\(title)  \(type)", attributes: [NSFontAttributeName:UIFont(name: "AvenirNext-DemiBold", size: 18.0)!])
        boldTitle.addAttribute(NSFontAttributeName, value: UIFont(name: "BodoniSvtyTwoSCITCTT-Book", size: 18.0)!, range: NSRange(location: title.characters.count + 2, length: type.characters.count))
        if (type == "free") {
            boldTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1.0), range: NSRange(location: title.characters.count + 2, length: type.characters.count))
        } else if (type == "cheap") {
            boldTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0, green: 0.75, blue: 1.0, alpha: 1.0), range: NSRange(location: title.characters.count + 2, length: type.characters.count))
        }

        //sets values for strings in cells
        cell.titleLabel.attributedText = boldTitle
        cell.lastConfirmedLabel.attributedText = boldLastConfirmed
        cell.postedLabel.attributedText = boldPosted

        //sets image based on post's status
        switch post.status {
        case 0:
            cell.statusImage.image = UIImage(named: "Help Filled-50.png")
        case 1:
            cell.statusImage.image = UIImage(named: "Good Quality Filled-50.png")
        case 2:
            cell.statusImage.image = UIImage(named: "Poor Quality Filled-50.png")
        case 3:
            cell.statusImage.image = UIImage(named: "Help Filled-50.png")
        default:
            NSLog("Unknown status code for post.")
        }
  }

最佳答案

您可以使用泛型来实现这一点。创建一个通用的 ArrayDataSource:

class ArrayDataSource<T: UITableViewCell, U: AnyObject> : NSObject, UITableViewDataSource {

    let items: [U]
    let cellIdentifier: String
    let configureCellBlock: (cell: T, item: U) -> ()

    init(items: [U], cellIdentifier: String, configureCellBlock: (cell: T, item: U) -> ()) {
        self.items = items
        self.cellIdentifier = cellIdentifier
        self.configureCellBlock = configureCellBlock
        super.init()
    }

    func itemAtIndexPath(indexPath: NSIndexPath) -> U {
        return items[indexPath.row]
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! T
        let item = self.itemAtIndexPath(indexPath)

        configureCellBlock(cell: cell, item: item)

        return cell
    }
}

像这样针对您的单元格和项目创建一个:

let postArrayDataSource = ArrayDataSource<postTableCell, Post>(items: posts, cellIdentifier: "tableCell", configureCellBlock: configurePostTableViewCell)

关于ios - UITableViewCell 子类的行为不像 UITableViewCells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36463014/

有关ios - UITableViewCell 子类的行为不像 UITableViewCells的更多相关文章

  1. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  2. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  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——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

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

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

  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. ruby - Ruby gsub 替换中的行为不一致? - 2

    两个gsub产生不同的结果。谁能解释一下为什么?代码也可在https://gist.github.com/franklsf95/6c0f8938f28706b5644d获得.ver=9999str="\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleVersion\n\t0.1.190\n\tAppID\n\t000000000000000"putsstr.gsub/(CFBundleVersion\n\t.*\.).*()/,"#{$1}#{ver}#{$2}"puts'--------'putsstr.gsub/(CFBundleVersio

  8. ruby-on-rails - Ruby 中意外的大小写行为 - 2

    我在一段非常简单的代码(如我所想)中得到了一个错误的值:org=4caseorgwhenorg=4val='H'endputsval=>nil请不要生气,我希望我错过了一些非常明显的东西,但我真的想不通。谢谢。 最佳答案 这是典型的Ruby错误。case有两种被调用的方法,一种是你传递一个东西作为分支的基础,另一种是你不传递的东西。如果您确实在case中指定了一个表达式语句然后评估所有其他条件并与===进行比较.在这种情况下org评估为false和org===false显然不是真的。所有其他情况也是如此,它们要么是真的,要么是假的。

  9. ruby - 使对象的行为类似于 ruby​​ 中并行分配的数组 - 2

    假设您在Ruby中执行此操作:ar=[1,2]x,y=ar然后,x==1和y==2。是否有一种方法可以在我自己的类中定义,从而产生相同的效果?例如rb=AllYourCode.newx,y=rb到目前为止,对于这样的赋值,我所能做的就是使x==rb和y=nil。Python有这样一个特性:>>>classFoo:...def__iter__(self):...returniter([1,2])...>>>x,y=Foo()>>>x1>>>y2 最佳答案 是的。定义#to_ary。这将使您的对象被视为要分配的数组。irb>o=Obje

  10. Ruby - 如何处理子类意外覆盖父类(super class)私有(private)字段的问题? - 2

    假设您编写了一个类Sup,我决定将其扩展为SubSup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:classSupdefinitialize@privateField="fromsup"enddefgetXreturn@privateFieldendendclassSub问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(superclass)。编辑:equivalentexampleinJava返回"fromSup",这也是它应该产生的答案。 最佳答案

随机推荐