誰かがこの時点まで読む勇気がある(または十分に絶望している)場合に備えて、ページの下部に適切な解決策を投稿します.
そのすべてのテキストを読みたくない人のための gitHub リポジトリは次のとおりです。
これは iOs7 で動作し (iOs8 でも動作すると思います)、自動レイアウトで動作します。マジックナンバーは必要なく、レイアウトを無効にしたり、そのようなものを使用したりできます。短くエレガントなソリューション。
私は、すべての制約関連のコードはupdateConstraints
メソッドに行くべきだと思います。それでは、自分で作ってみましょうResizableTextView
。
viewDidLoad
ここで最初に遭遇する問題は、メソッドの前に実際のコンテンツ サイズがわからないことです。フォント サイズや改行などに基づいて、長くてバグのある道をたどって計算することはできますが、堅牢なソリューションが必要なので、次のようにします。
CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];
これで、前か後かに関係なく、実際の contentSize がわかりviewDidLoad
ます。次に、textView に高さの制約を追加します (ストーリーボードまたはコードを介して、方法に関係なく)。その値を次のように調整しますcontentSize.height
。
[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
constraint.constant = contentSize.height;
*stop = YES;
}
}];
最後に行うことは、スーパークラスを に伝えることupdateConstraints
です。
[super updateConstraints];
クラスは次のようになります。
ResizableTextView.m
- (void) updateConstraints {
CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];
[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
constraint.constant = contentSize.height;
*stop = YES;
}
}];
[super updateConstraints];
}
きれいできれいですね。そして、コントローラでそのコードを扱う必要はありません!
ちょっと待って!
Y NO ANIMATION!
変更を簡単にアニメートして、textView
ストレッチをスムーズにすることができます。次に例を示します。
[self.view layoutIfNeeded];
// do your own text change here.
self.infoTextView.text = [NSString stringWithFormat:@"%@, %@", self.infoTextView.text, self.infoTextView.text];
[self.infoTextView setNeedsUpdateConstraints];
[self.infoTextView updateConstraintsIfNeeded];
[UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
[self.view layoutIfNeeded];
} completion:nil];