قم بتغيير حجم UITableViewCell إلى ارتفاع UILabel ديناميكيًا

StackOverflow https://stackoverflow.com/questions/1012361

سؤال

أريد تغيير حجم ارتفاع الخلية وفقًا لارتفاع الملصق وارتفاع الملصق وفقًا للنص.أم أن هناك أي طريقة يمكنني من خلالها تغيير حجم ارتفاع الخلية وفقًا للنص الذي تم إدخاله UITextView?

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

المحلول

تم إهمال هذه الطريقة منذ إصدار iOS 7.0.

هناك UITableView طريقة التفويض تسمى heightForRowAtIndexPath يتم استدعاؤه قبل إنشاء خلية أو جدول.

يمكنك استخدام NSIndexPath تم تمريره إليه للحصول على النص في صف معين واستخدام sizeWithFont الطريقة من UIStringDrawing.h لحساب أ CGSize لهذا الصف.

على سبيل المثال:

CGSize size = [text sizeWithFont:font
                   constrainedToSize:maximumLabelSize
                   lineBreakMode:UILineBreakModeWordWrap];

وأخيرا سوف تعود size.height.

نصائح أخرى

و- للiOS7 -

وإسناد هذا الخروج من الإجابة جوش فيرا ... وضع هذا في heightForRowAtIndexPath.

ولدي بيانات مائدتي المخزنة في NSArray * tableData.

// set the desired width of the textbox that will be holding the adjusted text, (for clarity only, set as property or ivar)
CGFloat widthOfMyTexbox = 250.0;

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Get a reference to your string to base the cell size on.
    NSString *cellText = [self.tableData objectAtIndex:indexPath.row];
    //set the desired size of your textbox
    CGSize constraint = CGSizeMake(widthOfMyTextBox, MAXFLOAT);
    //set your text attribute dictionary
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0] forKey:NSFontAttributeName];
    //get the size of the text box
    CGRect textsize = [cellText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    //calculate your size
    float textHeight = textsize.size.height +20;
    //I have mine set for a minimum size
    textHeight = (textHeight < 50.0) ? 50.0 : textHeight;

    return textHeight;
}

وأنا لم نجرب ذلك لدائرة الرقابة الداخلية <7، ولكن أعتقد أنه يجب أن تعمل لذلك أيضا.

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