字符串长度与给定的字体适合UITextView 2 - 返回 [英] String length with given font to fit UITextView 2 - The Return

查看:107
本文介绍了字符串长度与给定的字体适合UITextView 2 - 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题中,我要求一个好方法截断一个字符串以适合给定的UITextView。由于没有直接由SDK提供的方式,我最后写下面的递归方法(只由下面的公共方法调用)。然而,除非在计算字符串的高度时从字段宽度中减去一个15的因果系数(kFudgeFactor),否则这不起作用。如果我不这样做,返回的字符串实际上对于字段来说太长,并且在它下面显示一个额外的行。任何人都知道为什么,我应该真正使用,而不是这个fudge因子?

In this question I asked for a good way to truncate a string to fit a given UITextView. Since there was no way provided by the SDK directly, I've ended up writing the recursive method below (only called by the following public method). However, this doesn't work unless I subtract a fudge factor of 15 (kFudgeFactor) from the field width when calculating the string's height. If I don't do that, the string returned is actually too long for the field, and displays in an extra line below it. Anyone any idea why, and what I should really use instead of this fudge factor?

#pragma mark Size string to fit the new view

#define kFudgeFactor 15.0
#define kMaxFieldHeight 9999.0

// recursive method called by the main API
-(NSString*) sizeStringToFit:(NSString*)aString min:(int)aMin max:(int)aMax
{
if ((aMax-aMin) <= 1)
    {
    NSString* subString = [aString substringToIndex:aMin];
    return subString;
    }

int mean = (aMin + aMax)/2; 
NSString* subString = [aString substringToIndex:mean];

CGSize tallerSize = CGSizeMake(self.frame.size.width-kFudgeFactor,kMaxFieldHeight);
CGSize stringSize = [subString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];

if (stringSize.height <= self.frame.size.height)
        return [self sizeStringToFit:aString min:mean max:aMax]; // too small
else    
        return [self sizeStringToFit:aString min:aMin max:mean];// too big
}

-(NSString*)sizeStringToFit:(NSString*)aString
{

CGSize tallerSize = CGSizeMake(self.frame.size.width-kFudgeFactor,kMaxFieldHeight);
CGSize stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];

// if it fits, just return
if (stringSize.height < self.frame.size.height)
    return aString; 

// too big - call the recursive method to size it       
NSString* smallerString = [self sizeStringToFit:aString min:0 max:[aString length]];
return smallerString;   
}


推荐答案

UIScrollView 似乎在两边使用固定的8像素插入。这是独立于对齐或字体大小(基于测试和观察,而不是内部的任何明确的知识)。

UIScrollView seems to use a fixed 8-pixel inset on both sides. This is independent of alignment or font size (based on testing & observation, not any explicit knowledge of the internals).

所以看来你是正确的使用你的软糖因子,但应该 16.0 ,而不是 15.0

So it seems you are right to use your fudge factor, but it should probably be 16.0, not 15.0.

这篇关于字符串长度与给定的字体适合UITextView 2 - 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆