I am new to swift, I am trying to have a UITableView and the cells will be animated to appear one by one. How can I do that? Also, if the newly appeared row of cell not on the screen (hiding below the table). How can I move the table up when each cell appear?
var tableData1: [String] = ["1", "2", "3", "4", "5", "6", "7"]
override func viewWillAppear(animated: Bool) {
tableView.scrollEnabled=false
tableView.alpha=0.0
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "animateTable", userInfo: nil, repeats: false)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData1.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell
cell.lblCarName.textAlignment = NSTextAlignment.Justified;
return cell
}
func animateTable() {
//what should be the code?//
}
Step-1
In your cellForRowAtIndexPath method where initialize your cell, hide it like that;
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TblCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TblCell
cell.continueLabel.textAlignment = .justified
cell.contentView.alpha = 0
return cell
}
Step-2
Let's make fade animation. UITableViewDelegate has willDisplayCell method which is able to detect that when you scroll to top or bottom, first cell will display on the window.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.8, animations: {
cell.contentView.alpha = 1
})
}
Your fade animation is on the progress. The most important thing is that you can not setup your cell's alpha directly in runtime because iOS is doing some special internal handling with the cell as part of your UITableView and ignores your setup. So if you setup your cell's contentView, everything's gonna be fine.
In the UITableView, the rows are prepared automatically for you when they get to be in your "range vision". I'm assuming you are, at least not initially, being able to scroll the tableView, so we would scroll it programmatically making the rows appear as it goes. How are we doing that? Actually UITableView has a method that let us scroll it to a specific row:
scrollToRowAtIndexPath(indexPath : NSIndexPath, atScrollPosition : UITableViewScrollPosition, animated : Bool);
I'm too tired to write the code, so I'm going to try to explain. First, for every cell you set alpha to 0, as soon as they get loaded (cellForRowAtIndexPath).
Then let's suppose our screen fits the 5 first rows. You are going to animate their alphas sequentially (using UIView.animateWithDuration ) until the fifth one (index 4), then you are going to scrollToRowAtIndexPath passing NSIndexPath using 5, then 6,... until the rest of them (using scrollPosition = .Bottom). And for each of them, you would animate as soon as they get loaded. Just remember to put some time between this interactions. (animate first, run NSTimer to the second, and it goes on). And the boolean animated should be true of course.
To appear each visible cell one by one, you can do it by playing with alpha and duration value.
extension UITableView {
func fadeVisibleCells() {
var delayDuration: TimeInterval = 0.0
for cell in visibleCells {
cell.alpha = 0.0
UIView.animate(withDuration: delayDuration) {
cell.alpha = 1.0
}
delayCounter += 0.30
}
}
}
Here is some code which can get you started. In my COBezierTableView
I subclassed UITableView and override the layoutSubviewsmethod. In there you can manipulate the cells according to their relative position in the view. In this example I fade them out in the bottom.
import UIKit
public class MyCustomTableView: UITableView {
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
let indexpaths = indexPathsForVisibleRows!
let totalVisibleCells = indexpaths.count - 1
if totalVisibleCells <= 0 { return }
for index in 0...totalVisibleCells {
let indexPath = indexpaths[index]
if let cell = cellForRowAtIndexPath(indexPath) {
if let superView = superview {
let point = convertPoint(cell.frame.origin, toView:superView)
let pointScale = point.y / CGFloat(superView.bounds.size.height)
cell.contentView.alpha = 1 - pointScale
}
}
}
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell .alpha = 1.0
let transform = CATransform3DTranslate(CATransform3DIdentity, 0, 3000, 1200)
//let transform = CATransform3DTranslate(CATransform3DIdentity, 250, 0, 1250)
//let transform = CATransform3DTranslate(CATransform3DIdentity, 250, 1250, 0)
// let transform = CATransform3DTranslate(CATransform3DIdentity, -250, 300, 120)
cell.layer.transform = transform
UIView.animate(withDuration: 1.0) {
cell.alpha = 1.0
cell.layer.transform = CATransform3DIdentity
cell.layer.transform = CATransform3DIdentity
}
}
I think this method will be a great solution.
Set all cell alpha to 0
animate them in tableView(_:,willDisplay:,forRowAt:)
set a delay for every indexPath.row
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.05 * Double(indexPath.row), animations: {
cell.alpha = 1
})
}
Related
I've built an expandable Tableview and I want an arrow which points to the left when the cell is not expanded and down if the cell is expanded.
The first animation (To point the arrow down) Works like a charm. When trying to rotate back (while closing the expanded Cell), it just jumps back to normal without any animation.
In my cellForRow I do this:
cell.image1.rotate(item.opened ? -.pi/2 : 0, duration: 0.4)
I have an extension for it:
extension UIView {
func rotate(_ toValue: CGFloat, duration: CFTimeInterval) {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.toValue = toValue
animation.duration = duration
animation.isRemovedOnCompletion = false
animation.fillMode = CAMediaTimingFillMode.forwards
self.layer.add(animation, forKey: nil)
}
}
This one works like a charm outside of the tableview. But inside the Tableview it always goes back to normal without the animation.
Any idea where this comes from?
Call rotation in the action method instead of func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
Try the code below.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
cell.rotateArrow()
}
In CustomTableViewCell
class CustomTableViewCell: UITableViewCell {
#IBOutlet weak var arrowImageView: UIImageView!
var isOpened = false
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func rotateArrow() {
isOpened = !isOpened
arrowImageView.rotate(isOpened ? -.pi/2 : 0, duration: 0.4)
}
}
Ok I found the answer.
It jumped back (without any animation) because of how my rotate function was executed. Doing the animation when inputting 0 didn't work, because the image was set in the cell when it reloaded. So there was nothing to animate. Now I just set the picture and animate it afterwards.
if item.opened{
cell.image1.image = UIImage(named: "back")
cell.image1.rotate(-.pi/2, duration: 0.3)
} else {
cell.image1.image = UIImage(named: "down")
cell.image1.rotate(.pi/2, duration: 0.3)
}
I am trying to implement pagination in table view. so when fetching data from server, I want to get 10 data per request.
so the first time user opens the view, it will fetch 10 data, after the user scrolls to the 10th row, it will send request to get the data 11st to 20th.
but after fetching that 11-20th data and reloading the table view, it seems the table view drag down and it shows the last row (i.e the 20th row).
I want after the 10th row --> fetching data --> show the 11st row of the table view
so it will give smooth scrolling and good user experience
here is the simplified code i use. Thanks in advance
let numberOfDocumentsPerQuery = 5
var fetchingMore = false
var recommendedEventList = [EventKM]()
var lastDocumentFromQuery : QueryDocumentSnapshot?
extension HomeVC : UITableViewDelegate, UITableViewDataSource {
//MARK: - Table View Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recommendedEventList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
cell.eventData = recommendedEventList[indexPath.row]
return cell
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// to fetch more events if it comes to the bottom of table view
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if maximumOffset - currentOffset <= 10.0 {
if !fetchingMore {
getRecommendedEvents()
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toEventDetailVC", sender: nil)
}
}
func getRecommendedEventsFromBeginning() {
EventKM.observeRecommendedEvents (
selectedCity: selectedCity,
limit: numberOfDocumentsPerQuery) { (recommendedList, listener, lastDocument) in
if let events = recommendedList {
self.recommendedEventList = events
self.tableView.reloadData()
self.lastDocumentFromQuery = lastDocument
self.recommendedListener = listener
self.fetchingMore = false
} else {
self.fetchingMore = true // to stop fetching data
}
}
}
You can have a property to record the row that scroll to.
var rowForScroll = 1
every time you loaded data, add the rowForScroll
rowForScroll = rowForScroll + 10
let ip = NSIndexPath(forRow: rowForScroll, inSection: 0)
self.tableView.scrollToRowAtIndexPath(ip, atScrollPosition: .bottom, animated: true)
// Add your custom object.
recommendedEventList.add(customObject)
let numberOfRowsBeforeAPIRequest = tableView.numberOfRows(inSection: section)
let indexPath:IndexPath = IndexPath(row:(recommendedEventList.count - 1), section:0)
tableView.insertRows(at:[indexPath], with: .none)
// Do Validate if the actual indexpath exists or not, else will crash.
let ip = NSIndexPath(forRow: numberOfRowsBeforeAPIRequest + 1, inSection: 0)
tableView.scrollToRowAtIndexPath(ip, atScrollPosition: .bottom, animated: true)
Just putting what I am trying to do above.
Saving the number of Rows before reloading.
Adding new rows after the last row of the section.
Then scrolling 1 row down in the tableview.
I have table view. Inside cell I have method that animates view inside cell.
func animateCell() {
UIView.animate(withDuration: 0.4, animations: { [weak self] in
self?.quantityBackround.transform = CGAffineTransform(scaleX: 25, y: 25)
}) { [weak self] _ in
UIView.animate(withDuration: 0.1) {
self?.quantityBackround.transform = CGAffineTransform.identity
}
}
}
Also I have prepareForReuse()
override func prepareForReuse() {
quantityBackround.transform = CGAffineTransform.identity
}
The animation must work only for last cell when array of datasource changes and I do this in property observer like this (fires when something is being added to array)
guard let cell = checkTableView.cellForRow(at: IndexPath(row: viewModel.checkManager.check.count - 1, section: 0)) as? CheckItemTableViewCell else { return }
cell.animateCell()
All of this works fine.
One problem, is that I encounter is that when tableView is reloaded, all background views in all cells expand from zero size to its initial. Last cell animates ok.
I think that i miss something in prepareForReuse and because of this i see this glitch of inreasing from zero to initial size.
How to fix it ?
You need to implement this method of UITableViewDelegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//here check if your this cell is the last one, something like this
if (indexPath.row == yourDataSourceArray.count - 1)
{
if let customCell = cell as? CheckItemTableViewCell{
customCell.animateCell()
}
}
}
Hope this helps
I am trying to make a expandable table view (static cells). A container view is placed inside a cell below the "Lists of options" cell, as shown below:
The problem comes with the animation when expanding / collapsing. The topmost cell of each section will disappear briefly(hidden?), then reappear after the animation ends. I have later experimented and the results are as followed:
This will not happen when using tableView.reloadData().
This will happen when using tableView.beginUpdates() / endUpdates() pairs.
Hence I have come to the conclusion that this has sth to do with the animation. Below is my code and pictures for further explanation for said issue.
Code for hiding / showing
private func hideContainerView(targetView: UIView) {
if targetView == violationOptionsContainerView {
violationOptionContainerViewVisible = false
}
tableView.beginUpdates()
tableView.endUpdates()
UIView.animate(withDuration: 0.1, animations: { targetView.alpha = 0.0 }) { _ in
targetView.isHidden = true
}
}
private func showContainerView(targetView: UIView) {
if targetView == violationOptionsContainerView {
violationOptionContainerViewVisible = true
}
tableView.beginUpdates()
tableView.endUpdates()
targetView.alpha = 0.0
UIView.animate(withDuration: 0.1, animations: { targetView.alpha = 1.0 }) { _ in
targetView.isHidden = false
}
}
Table view
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
switch cell {
case violationTableViewCell:
if violationOptionContainerViewVisible {
hideContainerView(targetView: violationOptionsContainerView)
} else {
showContainerView(targetView: violationOptionsContainerView)
}
default: break
}
// tableView.reloadData()
// if we use this instead of begin/end updates, the cells won't disappear. But then we'll be ditching animation too.
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 3 {
if !violationOptionContainerViewVisible {
return 0.0
}
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
Images
Note that the first cell in each section ("FFFF" and the "slider bar") disappears and reappears during the animation
After searching for a few days, I have found the cause to this behavior.
I have, for some reason, set the cells layer.zposition below default zero. This will cause the cell to be seen "below" it's background view (hence disappeared) during the animation even though it's a subview of it.
Adjusting the value back to 0 or higher will remove this issue.
I am programmatically adding a UITableView as a subview of a view that uses UIView.animateWithDuration to expand the view when a button is clicked from a single point to a full window. Basically, a box that starts as a point and expands to full size with an animation. I am having difficulties getting the table to populate with cells. At first, a cell was being created, but would disappear after quickly after the animation completed, after playing around with it, I have gotten the cell to remain after the animation is complete, but now the cell disappears when I tap on it. I don't understand what is going on here. Can someone please help?
Here is my code. Note, I have removed what I believe to be irrelevant to this problem to make the code easier to read.
class PokerLogSelectionView: UIViewController {
let logSelectionTableViewController = LogSelectionTableViewController()
let logSelectionTableView = UITableView()
// Irrelevant class variables removed
init(btn : PokerLogSelectionButton){
// Irrelevant view initialization code removed
// Display the subviews
self.displayLogListScrollView()
}
func displayLogListScrollView() {
// Frame is set to (0,0,0,0)
let frame = CGRect(x: self.subviewClosed, y: self.subviewClosed, width: self.subviewClosed, height: self.subviewClosed)
logSelectionTableView.delegate = self.logSelectionTableViewController
logSelectionTableView.dataSource = self.logSelectionTableViewController
// Set the frame of the table view
logSelectionTableView.frame = frame
// Give it rounded edges
logSelectionTableView.layer.cornerRadius = 10
// Remove the cell divider lines
logSelectionTableView.separatorStyle = UITableViewCellSeparatorStyle.None
logSelectionTableView.backgroundColor = logSelectionViewContentScrollViewColor
self.view.addSubview(logSelectionTableView)
//self.logSelectionTableView.reloadData()
//self.addChildViewController(logSelectionTableViewController)
}
override func viewDidAppear(animated: Bool) {
// Create animation
let timeInterval : NSTimeInterval = 0.5
let delay : NSTimeInterval = 0
UIView.animateWithDuration(timeInterval, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
// Irrelevant code removed
// Set the size and position of the view and subviews after the animation is complete
self.view.frame = CGRect(x: self.frameXopen, y: self.frameYopen, width: self.frameWopen, height: self.frameHopen)
self.logSelectionTableView.frame = CGRect(x: self.subviewXopen, y: self.svYopen, width: self.subviewWopen, height: self.svHopen)
}, completion: { finished in
self.addChildViewController(self.logSelectionTableViewController)
})
}
}
class LogSelectionTableViewController : UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(LogSelectionCell.self, forCellReuseIdentifier: "logCell")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokerLibrary.logNames.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 20
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Selected row: \(indexPath.row)")
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell : LogSelectionCell = self.tableView.dequeueReusableCellWithIdentifier("logCell") as? LogSelectionCell {
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.textLabel!.text = pokerLibrary.logNames[indexPath.row].name
return cell
}
fatalError("Could not dequeue cell of type 'LogSelectionCell'")
}
}
Note: I can see the tableview after the animation is complete. The color is different than the view in the background view and the tableview does not disappear, just the cell. I expect there to be 1 cell, and I have printed out the number of rows in section 0 and it always returns 1.
Thanks for the help!
Edit:
Here is a screenshot of the view hierarchy before the cell disappears.
Here is a screenshot of the view hierarchy after I tap the cell and it disappears.
I overrode the touchesBegan method in my custom cell and did not call its superclass method. This stopped the cell from disappearing when I tap it, but it still disappears when I scroll the tableView.