[英]How to resize a UITextView according to the content, with fixed width
我必须以编程方式创建UITextView,但是在设置其大小时遇到了一些麻烦。
假设我有一句话,有多行:
s = @“ Hello World \\ nHello World \\ nHello World \\ n”;
现在,我想弄清楚要显示的高度,并相应地设置UITextView的高度(宽度需要固定)。 以下是我的代码:
CGSize size = [text sizeWithFont:_FONT_MYRIADPRO(20.0f) constrainedToSize:CGSizeMake(300, 1000)];
_textBox.text = text;
_textBox.frame = CGRectMake(10, 10, 300, size.height);
_textBox.font = _FONT_MYRIADPRO(20.0f);
_textBox.textColor = _COLOR_BLACK;
_textBox.backgroundColor = _COLOR_BLUE_DARK;
self.frame = CGRectMake(0, 0, 320, _textBox.frame.size.height + 2 * 10);
[self addSubview:_textBox];
但是,结果是这样的:
我尝试了许多其他方法,例如通话
[_textBox sizeToFit]
这也失败了,因为我想固定宽度。
我也试过
NSAttributedString *titleText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: _FONT_MYRIADPRO(20.0f)}];
CGRect bound = [titleText boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
_textBox.text = text;
_textBox.frame = CGRectMake(10, 10, 300, bound.size.height);
它也失败,结果与上图相同。
有人可以帮我吗?
我对此情况进行了一些测试。 我认为我们最好增加下降器并增加高度。 有关降序和前导含义的详细信息,请参阅https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/Introduction/Introduction.html 。
我的示例代码如下:
//
// RootViewController.m
// TextViewSize
//
// Created by AnkyHe on 11/13/13.
// Copyright (c) 2013 Gery Studio. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "RootViewController.h"
#define TextFont ([UIFont systemFontOfSize:20.0f])
static NSString *textContent = nil;
static NSUInteger const LineNum = 10;
@interface RootViewController ()
@property (nonatomic, weak) UITextView *textView;
@end
@implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSMutableArray *lines = [[NSMutableArray alloc] initWithCapacity:LineNum];
for (int i = 0; i < LineNum; ++i) {
[lines addObject:[NSString stringWithFormat:@"%d Hello world", i]];
}
textContent = [lines componentsJoinedByString:@"\n"];
self.view.backgroundColor = [UIColor whiteColor];
UITextView *textView = [[UITextView alloc] init];
self.textView = textView;
self.textView.text = textContent;
self.textView.font = TextFont;
[self.view addSubview:self.textView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
CGRect textRect = [textContent boundingRectWithSize:CGSizeMake(300, 1000)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:TextFont}
context:nil];
CGSize size = textRect.size;
self.textView.frame = CGRectMake(0, 0, 300, size.height + TextFont.descender + TextFont.leading);
self.textView.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
}
@end
输出如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.