2015-05-04 12 views
6

Tôi đã cố gắng tạo một ô động với nhãn bằng cách sử dụng nhanh để hỗ trợ IOS7 trong heightForRowAtIndexPath nhưng tôi chỉ tìm mã mục tiêu-c, có thể giúp người khác trợ giúp tôi viết lại mã này nhanh chóng?Chiều cao tùy chỉnh của UITableViewCell dựa trên độ dài văn bản nhãn trong Swift

// Fetch yourText for this row from your data source.. 
    NSString *yourText = [yourArray objectAtIndex:indexPath.row]; 

    CGSize lableWidth = CGSizeMake(300, CGFLOAT_MAX); // 300 is fixed width of label. You can change this value 
    CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping]; // You can put your desire font 

    // Here, you will have to use this requiredSize and based on that, adjust height of your cell. I have added 10 on total required height of label and it will have 5 pixels of padding on top and bottom. You can change this too. 
    int calculatedHeight = requiredSize.height+10; 
    return (float)calculatedHeight; 

chính xác tuyên bố này (làm thế nào để chuyển nó sang nhanh chóng):

CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping] 

tôi đã cố gắng chuyển đổi nó (nhưng nó không hoạt động như bản gốc Objective-C):

var requiredSize: CGSize = originalString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(19.0)]) 
+0

Dưới đây là ví dụ tốt nhất cho rằng chỉ cần đi qua it.http: //www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift –

+0

theo liên kết này: http://stackoverflow.com/questions/9827126/change-the-uitableviewcell-height-according-to-amount-of-text/42111135#42111135> – mumu

Trả lời

6

Có thể bạn có thể làm điều đó mà không cần UILabel nhưng điều này chỉ hoạt động tốt.

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 10000)) 
label.text = someText 
label.numberOfLines = 100 
label.font = UIFont(name: "Times New Roman", size: 19.0) 
label.sizeToFit() 
return label.frame.height + 10 
Các vấn đề liên quan