Ayar özel UITableViewCells yükseklik

oy
209

Bazı etiketleri, düğmeler ve görüntü manzarasına sahip bir özel UITableViewCell görüntülenecek kullanıyorum. Metin bir olan hücrede bir etiket vardır NSStringnesne ve dizenin uzunluğu değişken olabilir. Bu nedenle, ben de hücreye sabit bir yükseklik ayarlayamıyor UITableView'ın heightForCellAtIndexyöntemiyle. Hücrenin boyu kullanılarak belirlenebilir etiketin yüksekliğine bağlıdır NSStringsitesindeki sizeWithFontyöntemi. Ben bunu kullanarak çalıştı, ama yanlış yere gideceğim gibi görünüyor. Nasıl düzeltilebilir?

İşte hücreyi başlatılırken kullanılan koddur.

if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImage *image = [UIImage imageNamed:@dot.png];
    imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(45.0,10.0,10,10);

    headingTxt = [[UILabel alloc] initWithFrame:   CGRectMake(60.0,0.0,150.0,post_hdg_ht)];
    [headingTxt setContentMode: UIViewContentModeCenter];
    headingTxt.text = postData.user_f_name;
    headingTxt.font = [UIFont boldSystemFontOfSize:13];
    headingTxt.textAlignment = UITextAlignmentLeft;
    headingTxt.textColor = [UIColor blackColor];

    dateTxt = [[UILabel alloc] initWithFrame:CGRectMake(55.0,23.0,150.0,post_date_ht)];
    dateTxt.text = postData.created_dtm;
    dateTxt.font = [UIFont italicSystemFontOfSize:11];
    dateTxt.textAlignment = UITextAlignmentLeft;
    dateTxt.textColor = [UIColor grayColor];

    NSString * text1 = postData.post_body;
    NSLog(@text length = %d,[text1 length]);
    CGRect bounds = [UIScreen mainScreen].bounds;
    CGFloat tableViewWidth;
    CGFloat width = 0;
    tableViewWidth = bounds.size.width/2;
    width = tableViewWidth - 40; //fudge factor
    //CGSize textSize = {width, 20000.0f}; //width and height of text area
    CGSize textSize = {245.0, 20000.0f}; //width and height of text area
    CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:11.0f]
                        constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];

    CGFloat ht = MAX(size1.height, 28);
    textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
    textView.text = postData.post_body;
    textView.font = [UIFont systemFontOfSize:11];
    textView.textAlignment = UITextAlignmentLeft;
    textView.textColor = [UIColor blackColor];
    textView.lineBreakMode = UILineBreakModeWordWrap;
    textView.numberOfLines = 3;
    textView.autoresizesSubviews = YES;

    [self.contentView addSubview:imageView];
    [self.contentView addSubview:textView];
    [self.contentView addSubview:webView];
    [self.contentView addSubview:dateTxt];
    [self.contentView addSubview:headingTxt];
    [self.contentView sizeToFit];

    [imageView release];
    [textView release];
    [webView release];
    [dateTxt release];
    [headingTxt release];
}

Bu kimin yükseklik ve genişlik ters gidiyor etikettir:

textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
Oluştur 30/01/2009 saat 06:27
kaynak kullanıcı
Diğer dillerde...                            


9 cevaplar

oy
483

Sizin UITableViewDelegateuygulamalıdırtableView:heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 20;
}

Muhtemelen kullanmak isteyeceğiniz NSString'ın sizeWithFont:constrainedToSize:lineBreakMode:sadece indexPath bazı saçma matematik performans yerine, satır yüksekliğini hesaplamak için bir yöntem :)

Cevap 30/01/2009 saat 23:46
kaynak kullanıcı

oy
121

Tüm satır aynı yükseklikte ise, sadece set rowHeightuygulanması yerine UITableView özelliğini heightForRowAtIndexPath. Elma Dokümanlar:

heightForRowAtIndexPath: yerine rowHeight ait tableView kullanarak performans etkileri vardır. heightForRowAtIndexPath: bir tablo görünümü gösterilir, her zaman, o tableView çağırır Tablo incelemeler sıra (yaklaşık 1000 veya daha fazla) çok sayıda sahip önemli bir performans soruna neden olabilecek olan sırasının her biri için temsilci ilgilidir.

Cevap 19/01/2011 saat 00:59
kaynak kullanıcı

oy
22

özel bir Gönderen UITableViewCell Bu eklenti -controller

-(void)layoutSubviews {  

    CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

    self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
    self.frame = newCellViewFrame;

    [super layoutSubviews];
}

UITableView bu eklemek -controller

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 1.5; // your dynamic height...
}
Cevap 19/01/2010 saat 14:26
kaynak kullanıcı

oy
17
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath      *)indexPath;
{
   /// Here you can set also height according to your section and row
   if(indexPath.section==0 && indexPath.row==0)
   {
     text=@"pass here your dynamic data";

     CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

     CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]      constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

     CGFloat height = MAX(size.height, 44.0f);

     return height + (CELL_CONTENT_MARGIN * 2);
   }
   else
   {
      return 44;
   }
}

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UILabel *label = nil;

    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
       cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
    }
    ********Here you can set also height according to your section and row*********
    if(indexPath.section==0 && indexPath.row==0)
    {
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:UILineBreakModeWordWrap];
        [label setMinimumFontSize:FONT_SIZE];
        [label setNumberOfLines:0];
        label.backgroundColor=[UIColor clearColor];
        [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
        [label setTag:1];

        // NSString *text1 =[NSString stringWithFormat:@"%@",text];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        if (!label)
        label = (UILabel*)[cell viewWithTag:1];


        label.text=[NSString stringWithFormat:@"%@",text];
        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH          - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
        [cell.contentView addSubview:label];
    }
return cell;
}
Cevap 19/09/2012 saat 10:30
kaynak kullanıcı

oy
8
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    CGSize constraintSize = {245.0, 20000}
    CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize  lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18) 

   return 45
else return neededSize.height + 45 
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use  
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.

}
Cevap 18/11/2012 saat 17:20
kaynak kullanıcı

oy
5

Ben çözümlerin çok gördük ama tüm yanlış veya uncomplet oldu. Sen viewDidLoad ve Otomatik mizanpaj 5 çizgilerle tüm sorunları çözebilir. objetive C Bu:

_tableView.delegate = self;
_tableView.dataSource = self;
self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;

swift 2.0 için:

 self.tableView.estimatedRowHeight = 80
 self.tableView.rowHeight = UITableViewAutomaticDimension      
 self.tableView.setNeedsLayout()
 self.tableView.layoutIfNeeded()
 self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)

Artık gerek başka bir şey uygulamak veya geçersiz Bununla xib ile veya Film Şeridi 'nde tableview içine hücreyi oluşturmak. "- 250 Dikey İçerik Hugging Önceliği" eski sürüme ve alt etiketi (sınırlamak) (Don numarası os hatlarını 0 unutmak)

Burada görüntü açıklama girin Burada görüntü açıklama girin

Bir sonraki url kodunu İNDİRMEMENİZİ edebilirsiniz: https://github.com/jposes22/exampleTableCellCustomHeight

Kaynaklar: http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

Cevap 26/01/2016 saat 19:58
kaynak kullanıcı

oy
5

Bu konudaki tüm mesajlar sayesinde bir UITableViewCell ait rowHeight ayarlamak için bazı gerçekten yararlı yolları vardır.

İşte iPhone ve iPad için oluştururken gerçekten yardımcı herkesten kavramların bazılarının bir derlemesidir. Ayrıca farklı bölümlerine erişmek ve görünümleri değişen boyutlarına göre bunları ayarlayabilirsiniz.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 16;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 20;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
else
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 24;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 40;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
return 0;
} 
Cevap 22/03/2012 saat 21:02
kaynak kullanıcı

oy
3

Etiket artar metin olarak dinamik hücre yüksekliğe sahip için öncelikle metin kullanacağım yani yüksekliğini hesaplamak gerekir -heightForRowAtIndexPathtemsilci yöntemi ve (diğer lables, görüntülerin eklenen yükseklikleri ile iade metin + diğer statik yüksekliği maksimum yükseklik bileşenler olarak) ve hücre oluşturulması aynı yükseklik kullanılmaktadır.

#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f  
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{

    if (indexPath.row == 2) {  // the cell you want to be dynamic

        NSString *text = dynamic text for your label;

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        CGFloat height = MAX(size.height, 44.0f);

        return height + (CELL_CONTENT_MARGIN * 2);
    }
    else {
        return 44; // return normal cell height
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UILabel *label;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    }

    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];

    [label setNumberOfLines:2];

    label.backgroundColor = [UIColor clearColor];

    [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];

    label.adjustsFontSizeToFitWidth = NO;

    [[cell contentView] addSubview:label];


    NSString *text = dynamic text fro your label;

    [label setText:text];

    if (indexPath.row == 2) {// the cell which needs to be dynamic 

        [label setNumberOfLines:0];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];

    }
    return  cell;
}
Cevap 01/08/2012 saat 12:07
kaynak kullanıcı

oy
2

Hücre / Satır yüksekliğini düzeni için etkili hale getirmek için adımlar, otomatik boyut aşağıdaki sağlamak, satır yüksekliği ve tahmini satır yüksekliği için otomatik boyut ayarlamak için.

  • Ata ve tableview dataSource uygulamak ve temsilci
  • Ata UITableViewAutomaticDimensionrowHeight & estimatedRowHeight için
  • Temsilci / dataSource yöntemlerini uygulamak (IE heightForRowAtve bir değer iade UITableViewAutomaticDimensionbuna)

-

Amaç C:

// in ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

  @property IBOutlet UITableView * table;

@end

// in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.dataSource = self;
    self.table.delegate = self;

    self.table.rowHeight = UITableViewAutomaticDimension;
    self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewAutomaticDimension;
}

Swift:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

    // Set automatic dimensions for row height
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension
}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

UITableViewCell etiket Mesela

  • hatlar = 0 sayısını ayarlar (ve hat kesme modu = kuyruk kesecek)
  • Bunu Superview / hücre kabı ile ilgili tüm kısıtlamalar (üst, alt, sağdan sola) ayarlayın.
  • İsteğe bağlı : Eğer hiçbir veri olmasa da, etiket kapsadığı asgari dikey alanı istiyorsanız, etiket için asgari yükseklik ayarlayın.

Burada görüntü açıklama girin

Not : Eğer içeriği büyüklüğüne göre ayarlanmalıdır dinamik uzunluğu, birden fazla etiket (UIElements) bıraktıysanız: 'ayarlayın İçerik sarılma ve / genişletmek daha yüksek önceliğe sahip sıkıştırmak isteyen etiketler için Sıkıştırma Direnci Öncelikli`.

İşte bu örnekte ben ikinci (sarı) etiketin içeriği için daha öncelikli / önemini ayarlamak yol açar düşük sarılma ve yüksek sıkıştırma direnci önceliğini ayarlayın.

Burada görüntü açıklama girin

Cevap 02/02/2018 saat 15:20
kaynak kullanıcı

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more