开发者

How do I animate a UIButton in a UITableView?

开发者 https://www.devze.com 2023-01-03 08:31 出处:网络
I currently have a UITableView with each cell containing four UIButtons. I am placing an image for each button with a downloaded picture from online. I\'d like to have the button fade in when the imag

I currently have a UITableView with each cell containing four UIButtons. I am placing an image for each button with a downloaded picture from online. I'd like to have the button fade in when the image is finished downloading. 开发者_开发问答I know I can animate in the viewDidLoad, but I assign the image in the cellForRowAtIndex function. How do I go about animating just the UIButton at a later point in time when I update the UIButton with the image?


You should probably assign the UIButton a tag, maybe even define an integer tag to make it easy to read when you have four buttons.

#define CELL_BUTTON_ONE 9999

When you build the first button assign this tag:

[myButton setTag:CELL_BUTTON_ONE];
[cell addSubView:myButton];

Since I don't know where or how you load the images it is a bit hard to says what you should do. The idea is you get a reference to the UITableViewCell that owns the button you want to replace by an image. Anywhere you have a reference to a cell you can now go:

UIButton *buttonOne = [cell viewWithTag:CELL_BUTTON_ONE];
[button setImage:loadedImage];


Do it in -cellForRowAtIndexPath. When your image has finished downloading, you'll call -reloadData on your table view. You can create outlets for each UIButton in your cell or you can just assign them a tag. Set their alpha to 0.0 in IB. Then when -cellForRowAtIndexPath gets called, if the image for that row/button is available, set it's image and then call -setAlpha:1.0 in a UIView animation block. Something like:

- (UITableViewCell*)tableView:(UITableView*)tv 
        cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    // get a reference to your cell...

    // get reference to the UIButton in the cell
    UIButton *button = [cell viewWithTag:tagForButton];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.75];
    [button setAlpha:1.0f];
    [UIView commitAnimations];
}

The only issue I can think of is that you will need to keep track of the alpha value for a given indexPath based on your data due to cell re-use. So if your button1 in the current cell has already had it's alpha set to 1.0, you don't want to animate it again, but you will want to animate any other button's alpha that haven't been set yet. This image visibility state is something you will have to keep track of. It's not real hard to do, but there is more to it than just setting the alpha. Let me know if you need clarification.

0

精彩评论

暂无评论...
验证码 换一张
取 消