问题
I'm having troubles with my UITableView in swift on Xcode 6 :
I would like my UITableView cells to fade in / out when appearing / disappearing.
I looked a lot on the web for fade animations but I didn't find what I wanted because it's based on duration animations.
I Think what I need is sort of mask based on alpha ? I'm not sur and I don't even know have to create one...
I have a UIViewController containing a tableView and some blank space (for now) upside and downside of the UITableView.
Thank's for your help !!
Best,
Anatole
回答1:
animateWithDuration seems appropriate, since the fade in/out has a duration: the cell gradually becoming visible or invisible over time.
Here is an example of making table cells fade-in:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
cell.backgroundColor = UIColor.grayColor()
cell.alpha = 0
UIView.animateWithDuration(2, animations: { cell.alpha = 1 })
return cell
}
EDIT:
This sets the cell's alpha based on their y position, which is probably closer to what you want:
func scrollViewDidScroll(scrollView: UIScrollView) {
for cell in tableView.visibleCells() as [UITableViewCell] {
var point = tableView.convertPoint(cell.center, toView: tableView.superview)
cell.alpha = ((point.y * 100) / tableView.bounds.maxY) / 100
}
}
回答2:
I was looking for the same thing, I ended up making my own and I thought I'd share it:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let cellCount = tableView.visibleCells.count
let alphaInterval:CGFloat = 1.0 / CGFloat(cellCount / 2)
for (index,cell) in (tableView.visibleCells as [UITableViewCell]).enumerated() {
if index < cellCount / 2 {
cell.alpha = CGFloat(index) * alphaInterval
} else {
cell.alpha = CGFloat(cellCount - index) * (alphaInterval)
}
}
}
and here is the cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = countries[indexPath.row].uppercased()
cell.textLabel?.textColor = .white
cell.backgroundColor = .clear
cell.alpha = 0.25
UIView.animate(withDuration: 0.5, animations: {
cell.alpha = 1
})
return cell
}
Ends up looking like this:
来源:https://stackoverflow.com/questions/29409405/swift-fading-cells-in-uitableview