我认为你是对的——我无法-[NSAttributedString boundingRectWithSize:options:context: ]
返回一个适用于所有字体大小的值......
但是,我确实得到了一个 UILabel 来正确调整大小并绘制属性字符串:
- 将您的文本视图类更改为
UILabel
-setAttributedText:
在标签上使用
- 设置
label.numberOfLines = 0
(多行)
- 在
-layoutSubviews
标签的超级视图调用中 -[ label sizeThatFits: ] 以获取标签的正确大小....
为我工作...
编辑:这是我的 ViewController.m 文件:
@interface View : UIView
@property ( nonatomic, strong ) UITextView * textView ;
@property ( nonatomic, strong ) UISlider * fontSizeSlider ;
@end
@implementation View
-(void)layoutSubviews
{
CGRect bounds = self.bounds ;
self.textView.layer.anchorPoint = (CGPoint){ 0.0f, 0.5f } ;
self.textView.layer.position = (CGPoint){ CGRectGetMinX( bounds ), CGRectGetMidY( bounds ) } ;
self.textView.bounds = (CGRect){ .size = [ self.textView sizeThatFits:bounds.size ] } ;
self.fontSizeSlider.frame = CGRectMake(5, CGRectGetMaxY(bounds) - 30, bounds.size.width - 10, 25) ;
}
@end
@interface ViewController ()
@end
@implementation ViewController
-(void)loadView
{
self.view = [[ View alloc ] initWithFrame:CGRectZero ] ;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableAttributedString * aString = [[ NSMutableAttributedString alloc ] initWithString:@"Some test text in a scaling text view" ] ;
NSDictionary * attributes = @{ NSForegroundColorAttributeName : [ UIColor redColor ] } ;
[ aString setAttributes:attributes range:(NSRange){ 5, 4 } ] ;
textView = [[UITextView alloc] initWithFrame:CGRectZero];
[textView setAttributedText:aString ];
[textView setFont:[UIFont systemFontOfSize:18]];
[textView setCenter:CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds))];
((View*)self.view).textView = textView ;
[self.view addSubview:textView];
[textView release];
UISlider * fontSizeSlider = [[UISlider alloc] initWithFrame:CGRectMake(5, CGRectGetMaxY(self.view.bounds) - 30, self.view.bounds.size.width - 10, 25)];
[fontSizeSlider addTarget:self action:@selector(fontSizeSliderDidChange:) forControlEvents:UIControlEventValueChanged];
[fontSizeSlider setMinimumValue:5];
[fontSizeSlider setMaximumValue:100];
[fontSizeSlider setValue:textView.font.pointSize];
((View*)self.view).fontSizeSlider = fontSizeSlider ;
[self.view addSubview:fontSizeSlider];
[fontSizeSlider release];
}
- (void)fontSizeSliderDidChange:(UISlider *)sender {
[ textView setFont:[textView.font fontWithSize:sender.value]];
[ self.view setNeedsLayout ] ;
}
@end