UITextView how to cut off text

六眼飞鱼酱① 提交于 2019-12-13 00:18:06

问题


I have a UITextView that is displaying a facebook status loaded from Facebook Connect. I'm trying to make it so that the UITextView is just creating a preview of the text. I want it to look like it does when there is too much text for a UILabel. It would be something like "There is too much text..." with the dots but UITextViews don't do that. Does anybody know how to get it to work?


回答1:


Write a separate method that counts how many letters there are in the string and if there are more than some preset value then cut it and append three dots to the end.

Also, consider using UILabels instead of UITextViews if you don't need to edit information inside since UITextViews take longer to allocate and init and are generally slower than UILabels.




回答2:


+(NSString *)getTruncatedTextForString:(NSString *)inputString withFont:(UIFont *)font withLength:(int)textViewlength 
{

    CGSize dotSize=[@"..." sizeWithFont:font];
    float dotWidth=dotSize.width;
    NSString *outputString=@"";

    int reqLength=textViewlength-dotWidth;

    for(int i=0;i<inputString.length;i++) 
    {

        NSString *tempStr=[outputString stringByAppendingString:[inputString substringWithRange:NSMakeRange(i,1)]];

        if([tempStr sizeWithFont:font].width>reqLength)
        {
            break;
        }
        else 
        {
            outputString=tempStr;
        }
    }
    NSString *tempStr=[outputString stringByAppendingString:@"..."];
    outputString=tempStr;
    return outputString; 
}



回答3:


Try the below code. It will display two dots to the textview with text more than its frame height.

if(textview.contentSize.height > textview.frame.size.height)
{

    while (textview.contentSize.height > textview.frame.size.height)
    {
        textview.text = [textview.text substringWithRange:NSMakeRange(0, textview.text.length-1)];
    }
    textview.text = [textview.text substringWithRange:NSMakeRange(0, textview.text.length-2)];
    textview.text= [NSString stringWithFormat:@"%@..",textview.text];
}

It works, only when we set the correct height to the UITextview with respect to the font and fontsize of that textview.
For ex, if the font is bold system font of size 16 means, the textview height should be of minimum 30.



来源:https://stackoverflow.com/questions/4925081/uitextview-how-to-cut-off-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!