简体   繁体   中英

How to position a UIActivityIndicatorView in a UITableViewCell

I've this code for adding UIActivityIndicatorView to a UITableViewCell .

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    UIImage *spacer = [UIImage imageNamed:@"spacer"];
    UIGraphicsBeginImageContext(CGSizeMake(220, 150));
    [spacer drawInRect:CGRectMake(0,0,spinner.frame.size.width,spinner.frame.size.height)];
    UIImage* resizedSpacer = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    cell.imageView.image = resizedSpacer;
    [cell.imageView addSubview:spinner];
    [spinner startAnimating];

Currently the image is shown in the top left of the 220x150 box. Instead I would like to put it in center. How can I do that? I've tried to change the two first parameters on CGRectMake , but that didn't change anything.

You've added resizedSpacer as the imageView without actually doing anything to spinner 's frame. You want something like:

CGSize spinSize = spinner.frame.size;
spinner.frame = CGRectMake((220-spinSize.width)/2., (150-spinSize.height)/2.,spinSize.width, spinSize.height);
[cell.imageView addSubview:spinner];

I don't think that the logic involving spacer is required. In fact, you may not even want to host the UIActivityIndicatorView in the UIImageView at all; why not position it directly within the tableview cell?

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