我使用自动布局以编程方式添加了UITextView
。我想根据文字大小调整UITextView
的大小。我尝试了一些代码,但它没有工作,如果有人帮忙我会很感激。
#import "AutoGrowingTextView.h"
@implementation AutoGrowingTextView
- (void) layoutSubviews
{
[super layoutSubviews];
if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {
[self invalidateIntrinsicContentSize];
}
}
- (CGSize)intrinsicContentSize
{
CGSize intrinsicContentSize = self.contentSize;
// iOS 7.0+
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
intrinsicContentSize.width += (self.textContainerInset.left + self.textContainerInset.right ) / 2.0f;
intrinsicContentSize.height += (self.textContainerInset.top + self.textContainerInset.bottom) / 2.0f;
}
return intrinsicContentSize;
}
@end
#import "ViewController.h"
#import "AutoGrowingTextView.h"
@interface ViewController ()
{
AutoGrowingTextView * TextView;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
TextView = [AutoTextView new];
TextView.translatesAutoresizingMaskIntoConstraints = NO;
TextView.backgroundColor = [UIColor colorWithRed:0.95 green:0.47 blue:0.48 alpha:1.0];
TextView.scrollEnabled = NO;
[TextView layoutSubviews];
[self.view addSubview:TextView];
NSLayoutConstraint * constraint2 = [NSLayoutConstraint constraintWithItem:TextView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem: self.view attribute:NSLayoutAttributeTop multiplier:1.0f constant:20.0f];
[self.view addConstraint:constraint2];
constraint2 = [NSLayoutConstraint constraintWithItem:TextView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:5.0f];
[self.view addConstraint:constraint2];
constraint2 = [NSLayoutConstraint constraintWithItem:TextView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-5.0f];
[self.view addConstraint:constraint2];
constraint2 = [NSLayoutConstraint constraintWithItem:TextView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem: nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:50.0f];
[self.view addConstraint:constraint2];
}
@end
答案 0 :(得分:0)
这听起来有点疯狂,但我相当确定如果你删除了高度约束,那么布局引擎会调整UITextView的大小以适应字体大小。我上周遇到了同样的问题,这就解决了这个问题。
删除此约束,看看它是否有效:
constraint2 = [NSLayoutConstraint constraintWithItem:TextView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem: nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:50.0f];
让我补充一点,你应该为textView定义一个字体,这可能是你在调整大小时获胜的门票