【问题标题】:sizeWithFont:constrainedToSize: Doesn't count "\n" in NSStringsizeWithFont:constrainedToSize: 不计算 NSString 中的 "\n"
【发布时间】:2014-07-09 20:03:01
【问题描述】:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString *substring = textView.text;
    substring = (text.length == 0 && range.length == 1) ?
    [substring substringToIndex: substring.length-1] : [substring stringByAppendingString: text];

    CGSize size = [substring sizeWithFont:textView.font
                        constrainedToSize:CGSizeMake(textView.frame.size.width, 200.0)];

    CGFloat height = MAX(size.height, firstHeight);

    if(height != lastHeight)
    {
        CGFloat y = height - lastHeight;
        CHANGE_HEIGHT(textView, height);
        lastHeight = height;
    }   
    return YES;
}

问题是 sizeWithFont:constrainedToSize: 给了我错误的高度。 例如,如果文本是 "Hello \n"sizeWithFont 将不计入 "\n", 所以 "Hello""Hello \n" 文本在相同的高度

任何需要的帮助将不胜感激!

【问题讨论】:

  • 如果在\n后面加一个空格怎么办? “你好\n”
  • Tnx!它现在正在工作:)

标签: ios objective-c nsstring uitextview sizewithfont


【解决方案1】:

不相关,但您获取substring 的方式忽略了修改文本的范围。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString *textToMeasure = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if ([textToMeasure hasSuffix:@"\n"]) {
        textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多