سؤال

أريد إنشاء UITableView بارتفاعات مختلفة للصفوف، وأحاول تحقيق ذلك عن طريق إنشاء UILabels داخل UITableViewCells.

هذا هو الكود الخاص بي حتى الآن:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"EntryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }

    UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
    textView.numberOfLines = 0;
    textView.text = [entries objectAtIndex:[indexPath row]];
    [cell.contentView addSubview:textView];
    [textView release];

    return cell;
}

هذا يعطيني سطرين من النص لكل خلية.ومع ذلك، يحتوي كل "إدخال" على عدد مختلف من الأسطر، وأريد تغيير حجم UITableViewCells تلقائيًا، وتغليف النص حسب الضرورة، دون تغيير حجم الخط.

[textView sizeToFit] و/أو [cell sizeToFit] لا يبدو أن العمل.

إليك كيف أريد أن يبدو UITableView:

----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------

هل يعرف أحد كيفية القيام بذلك بشكل صحيح؟

شكرًا.

هل كانت مفيدة؟

المحلول

يحدد UITableViewDelegate طريقة اختيارية heightForRowAtIndexPath، والتي ستساعدك على البدء.تحتاج بعد ذلك إلى استخدام sizeWithFont.

هناك بعض المناقشات لمشكلتك المحددة هنا:

http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/

تمت مناقشة حجم النص أيضًا في هذا الموضوع

نصائح أخرى

هذا الرمز يعمل بالنسبة لي.لا أعرف إذا كانت مثالية، ولكنها تعمل.

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

    if(indexPath.row<[notesModel numberOfNotes]){
        NSString *cellText = [@"Your text..."];
        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:12.0];
        CGSize constraintSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 100, MAXFLOAT);
        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

        return labelSize.height + 20;
    }
    else {
        return 20;
    }
}

textView.numberOfLines = 2؟يقوم numberOflines بتعيين الحد الأقصى لعدد الخطوط، لذا ربما يكون هناك خطان مناسبان لك؟

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top