Monotouch: UITableViewCell height

2019-05-11 14:20发布

问题:

I've been surfing the net to figure out how make my tablecell height fitt its content (my content is of different height).

I've tried to look at this sample .... http://simon.nureality.ca/simon-says-project-d-uitableviewcells-autosize-based-on-text-height-in-monotouch-heres-how/ ... but I can't make it work.

Here's my code so far .. the cell height is actually working, but the text is centered with trailling dotts (instead of dilling out the entire frame):

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
    string item = this.Lst.Items [indexPath.Section];

    UITableViewCell cell = tableView.DequeueReusableCell (_cellIdentifier);
    if (cell == null) {
        cell = new UITableViewCell (UITableViewCellStyle.Default, _cellIdentifier);
        cell = new UITableViewCell (UITableViewCellStyle.Subtitle, _cellIdentifier);
    }

    // Find the height...
    SizeF textWidth = new SizeF (tableView.Bounds.Width - 40, float.MaxValue);
    SizeF textSize = tableView.StringSize(item, Font, textWidth, LineBreakMode);

    // Textlabel...
    cell.TextLabel.Text = item;
    cell.TextLabel.Font = Font;
    cell.TextLabel.Frame = new RectangleF(cell.TextLabel.Frame.X, cell.TextLabel.Frame.Y, textSize.Width, textSize.Height);

    //cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
    cell.ImageView.Image = PlaceholderImage;   
    cell.EditingAccessory = UITableViewCellAccessory.DisclosureIndicator;

    // Sizing the cell...
    RectangleF rectCell = cell.Frame;
    rectCell.Height = textSize.Height;
    cell.Frame = rectCell;

    return cell;
}

public override float GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
    string item = this.Lst.Items [indexPath.Section];
    SizeF size = new SizeF (tableView.Bounds.Width - 40, float.MaxValue);
    float height = tableView.StringSize (item, Font, size, LineBreakMode).Height + 10;
    return height;
}

And it looks like this...

Any idea what is wrong?

Thanks!

Mojo

回答1:

You can control the textlabel's behavior by setting the Lines and LineBreakMode properties.

For example, setting

cell.TextLabel.Lines = 0;
cell.TextLabel.LineBreakMode = UILineBreakMode.WordWrap; 

will let your label do word wrapping and use as many lines as needed.

Also consider using MonoTouch.Dialog by Miguel De Icaza. It simplifies dealing with UITableView considerably.