简体   繁体   中英

Cocoa iOS/Touch: Keeping a subview of the UITableViewCell contentView right-aligned

Let's say I have a UITableView that

  1. is part of an iPad app
  2. doesn't use the whole screen
  3. changes its width, depending on the state of the app and other views

I added an extra subview (let's say an UILabel) to the UITableView's cell's contentView. I want the UILabel's right border to be 10 pixels from the right cell border at all times.

I managed to do this for an initial drawing of the table view for any width by specifically setting the cells frame after dequeuing it which also updates the contentView's width (otherwise the cells seem to be 320 pixels wide all the time).

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (cell == nil) {
    cell = [[[UITableViewCell alloc]
             initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
    CGRect oldFrame = cell.frame;
    cell.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, tableview.frame.size.width, oldFrame.size.height);

    /* and other stuff */
}

Question: How can I keep the subviews of the cell's contentView aligned to the cell's right border when the table view's size changes at runtime?

You could try setting your cell autoresizingMask and its autoresizesSubviews properties?

Possibly this would work:

cell.contentView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth;
cell.contentView.autoresizesSubviews = YES;

you should also set the autoresizingMask of your UILabel , I think:

label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth;

Here the docs .

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