简体   繁体   中英

How do I horizontally center a UIImageView in a UITableViewCell?

I am having trouble centering a 200x200 image horizontally inside a customized UITableViewCell . I have set the tableViewheightForRowAtIndexPath in the UITableViewDelegate to the appropriate value, but that doesn't center my image horizontally, it does so only vertically (better than nothing I guess). I also tried to change the value of the imageView.frame in layoutSubviews in my customized cell, but that doesn't seem to have any effect. I have even commented it out, placed it before [super layoutSubviews]; , played around with the values of the frame, but I keep getting the same result.

Can anyone help me with this? What code should I write to achieve such an effect? Thanks.

You will try this code its help you

You need to subclass UITableViewCell and override layoutSubviews, as follows:

- (void) layoutSubviews
{   
    [super layoutSubviews];

    self.imageView.frame = CGRectMake( 10, 10, 50, 50 ); // your positioning here
}

In your cellForRowAtIndexPath: method, be sure to return an instance of your new cell type.

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 UIImageView *imgView; 
 if(cell == nil)
 {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

   imgView = [[UIImageView alloc] initWithFrame:(100,0,100,62)];
    [imgView setImage:[UIImage imageNamed:@"img.png"]];
    imgView.tag = 55;
    [cell.contentView addSubview:imgView];
    [imgView release];
 } 
 else
 {
        imgView = (id)[cell.contentView viewWithTag:55];
 }

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