Call Objective-C function in Swift 3

2019-09-13 00:24发布

I am embeding JBParallaxCell, a UITableViewCell subclass. I want to call a function:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // Get visible cells on table view.
    NSArray *visibleCells = [self.tableView visibleCells];

    for (JBParallaxCell *cell in visibleCells) {
        [cell cellOnTableView:self.tableView didScrollOnView:self.view];
    }
}

I converted this code to Swift:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleCells = table.visibleCells
    var cells : JBParallaxCell?

    for cells in visibleCells {
        cells(on: table, didScrollOn: self.view)
        // cells.cellOnTableView(tableView: table, didScrollOn: self.view)
    }
}

They give error call not function of UITableViewCell

2条回答
做个烂人
2楼-- · 2019-09-13 00:48

If your tableview outlet is called table, then you'd could do:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    for cell in table.visibleCells {
        if let cell = cell as? JBParallaxCell {
            cell.cell(on: table, didScrollOn: view)
        }
    }
}

Or, equivalent:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    for cell in table.visibleCells {
        (cell as? JBParallaxCell)?.cell(on: table, didScrollOn: view)
    }
}
查看更多
Emotional °昔
3楼-- · 2019-09-13 01:08

You need to convert [cell cellOnTableView:self.tableView didScrollOnView:self.view]; to swift and add it in JBParallaxCell. I converted it myself

      func cellOnTableView(tableView: UITableView, didScrollOn view: UIView) {
         let rectInSuperview: CGRect = tableView.convert(frame, to: view)

         let distanceFromCenter: Float = Float(frame.height / 2 - rectInSuperview.minY)
         let difference: Float = Float(parallaxImage.frame.height - frame.height);
         let  move: Float = (distanceFromCenter / Float(view.frame.height)) * difference

         var imageRect: CGRect = parallaxImage.frame
         imageRect.origin.y = CGFloat(move - (difference / 2))
         self.parallaxImage.frame = imageRect
}

And change this line let visibleCells = table.visibleCells to

if let visibleCells = table.visibleCells as? JBParallaxCell
查看更多
登录 后发表回答