简体   繁体   中英

Swift animate view in tableviewcell

For an app that I'm developing, I'm using a tableview. My tableview, has of course a tableviewcell. In that tableviewcell I'm adding a view programmatically (so nothing in storyboard). It's a view where I draw some lines and text and that becomes a messagebubble. If the messagebubble is seen by the other user you sent it too , a line of the bubble will go open.

So I have the animation function inside the class of that UIView (sendbubble.swift)

Now, it already checks if it is read or not and it opens the right bubble. But normally it should animate (the line that goes open should rotate) in 0.6 seconds. But it animates instantly. So my question is, how do I animate it with a duration?

I would also prefer to still call it in my custom UIView class (sendbubble.swift) . Maybe I need code in my function to check if the cell is presented on my iphone?

Thanks in advance!

func openMessage() {
    UIView.animate(withDuration: 0.6, delay: 0.0, options: [], animations: {
        var t = CATransform3DIdentity;
        t = CATransform3DMakeRotation(CGFloat(3 * Float.pi / 4), 0, 0, 1)
        self.moveableLineLayer.transform = t;
    }, completion:{(finished:Bool) in })
}

You need to implement the UITableViewDelegate method tableView(_:willDisplay:forRowAt:) https://developer.apple.com/reference/uikit/uitableviewdelegate/1614883-tableview

That is triggered when the cell is about to be drawn - not when it is created. You will also need to store a state in your model that says if the animation has occurred, otherwise it will happen every time the cell comes back into view.

EXAMPLE

In the view controller (pseudo code)

class CustomViewController: UITableViewDelegate {
    //where ever you define your tableview
    var tableView:UITableView
    tableView.delegate = self

    var dataSource //some array that is defining your cells - each object has a property call hasAnimated

    func tableView(_ tableView: UITableView, willDisplay cell: ITableViewCell, 
           forRowAt indexPath: IndexPath) {
        if let cell = cell as? CustomTableViewCell, dataSource[indexPath.row].hasAnimated == false {
            dataSource[indexPath.row].hasAnimated = true
            cell.openMessage()
        }
    }
}

class CustomTableViewCell: UITableViewCell {
    func openMessage() { //your method
    }
} 

First you need to grab the cell.

  1. Get the indexPath of that cell where you need to show open bubble.
  2. Get the cell from tableView.cellForRowAt(at:indexPath)
  3. We will now have access to that bubble view now you can animate using the same function func openMessage()

Any question? comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM