问题
I have created a couple of different UITableViewCell
s for my tableViewController
, this is because I have different bits of data I want to display depending what comes back. Because of this each UITableViewCell
is of a different height.
This is all fine, However one of my UILabel
s has to display a large NSString
, so large that I have had to word wrap it onto a second line, The only issue here is that it messes up my UITableViewCell
formatting.
My question is, is it possible to flag or capture some type of action when a UILabel
receiving a NSString
has to use wordrap because the size of the NSString
is too long?
Or is there a way to calculate the physical length (not how many chars are in the string) of the NSString
so I can decide hey I need to reformat my UITableViewCell
..
Any help would be greatly appreciated.
回答1:
The usual way is to use sizeWithFont:constrainedToSize:lineBreakMode: to get the size of a string. You use it like this:
CGSize stringSize = [theString sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:12] constrainedToSize:CGSizeMake(320, 3000) lineBreakMode:NSLineBreakByWordWrapping ];
This is set for the full width of a table cell, but you would want to use the width of your label instead.
回答2:
i dont know if i understand well but you have the height of your tableviewcell right? and you have a NSString maybe in a UITextView and this height of content of textview is higher then tableviewcell. Well, you should first calculate the content of UITextview, add into a list and when heightforRowAtindexPath was called, you should calculate new height (content textview) plus something... And to solve the max length you should count a limit for chars or limit for lines..
Some usefull code:
//resize height with content of UITextView
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
//delegate textview to calculate limit for text.
- (void)textViewDidChange:(UITextView *)textView{
NSInteger restrictedLength=140;
NSString *temp=textView.text;
if([[textView text] length] > restrictedLength){
textView.text=[temp substringToIndex:[temp length]-1];
}
}
remember, you need to calculate the limit/size content from UITextview before heightforRowAtIndexPath called. When it called you already need to know your max height for cell.
来源:https://stackoverflow.com/questions/14866534/how-to-find-out-when-uilabel-wordwraps