简体   繁体   中英

UIView transform inside a UITableViewCell does not work

I have this up arrow button inside a UITableViewCell that should rotate 180 degrees when clicked or when the method gets called somewhere else. This actually works when you click the button and update the sender.transform.

@IBAction func rotate(sender: UIButton) {

if (top)
{
    UIView.animateWithDuration(0.5, animations: {
        sender.transform = CGAffineTransformMakeRotation((360.0 * CGFloat(M_PI)) / 180.0)
    })

}
else
{
    UIView.animateWithDuration(0.5, animations: {
        sender.transform = CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 180.0)
    })

}

}

If I change the code so that I reference the button instead from the UITableViewCell to something like this, this does not work. The button does not rotate.

IBAction func rotate(sender: UIButton) {

let detailCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! DetailCell

if (top)
{
    UIView.animateWithDuration(0.5, animations: {
        detailCell.arrowButton.transform = CGAffineTransformMakeRotation((360.0 * CGFloat(M_PI)) / 180.0)
    })

}
else
{
    UIView.animateWithDuration(0.5, animations: {
        detailCell.arrowButton.transform = CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 180.0)
    })

}

}

Basically, I want to be able to rotate the button from the UITableViewCell in another method that does not involve clicking the button, so I need to be able to reference the button from the UITableViewCell and rotate it. What is the right way to do this?

You have a couple of different choices.

If you create a custom subclass of UITableViewCell then you can add an outlet to you button to the cell. Ask the table view for the cell, cast it to to your custom class, and then use the outlet to the button ( myCustomCell.button ).

The other option is to add a unique tag to the button, and then use cell.contentView.viewWithTag(tagNumber) . Then cast the result from UIView to UIButton.

Using a custom subclass of UITableViewCell and an outlet is cleaner and less fragile, but more work to set up.

At least, Duncan got me in the right track by suggesting to do print out. Anyway, once I realized the sender and the arrowButton from the cell have different addresses and it at least rotates once in the cellForRowAtIndexPath, I decided to save that first arrowButton object somewhere else, and then uses that for the transform. Something like this:

var saveArrowButton: UIButton?

At the cellForRowAtIndexPath delegate method:

 if (saveArrowButton == nil)
 {
     saveArrowButton = detailCell.arrowButton
  }

And in the rotate method: I am referencing saveArrowButton!.transform. That seems to work so far.

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