简体   繁体   中英

How can I center image in custom cell

In my custom cell I want to center an image but this does not work.

    self.leftImage = [[[UIImageView alloc] initWithImage:cry] autorelease] ;
    float h=cell.frame.size.height;
    float w=cell.frame.size.width;

    CGRect r = leftImage.frame;
    r.origin = cell.frame.origin;
    r.origin.x = w/ 2  - r.size.width / 2;
    r.origin.y = h / 2  - r.size.height / 2 + 12;
    leftImage.frame = r;
            [self.contentView addSubview:leftImage];

Try setting the leftImage 's autoresizingMask :

self.leftImage.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin

When the cell is created, you're never sure what its dimensions are. Mostly, a cell will be initialized with a CGRectZero frame and later on, the UITableView will resize the cell appropriately.

I think You tried to do this in - (UITableViewCell *)tableView:(UITableView *)tableViewRef cellForRowAtIndexPath:(NSIndexPath *)indexPath when creating new cell or in cell itself in init section. At this moments cell don't have correct frame and you can't rely on it.

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