问题
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
回答1:
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)
}
}
回答2:
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
来源:https://stackoverflow.com/questions/41259059/call-objective-c-function-in-swift-3