質問

いい方法はありませんかのサイズを調整するには、 UITextView に準拠してそのコンテンツ?うためのインスタンスしてい UITextView この一行のテキスト:

"Hello world"

その後、一行のテキスト:

"Goodbye world"

いい方法はありませんかアタッチを rect を保持したすべての行のテキストビューでの調整ができ親ビューに従って?

別の例として、次の注意事項の分野でのイベントカレンダーの申請-承どのように細胞の UITextView 含む)を拡張し、すべての行のテキストの注意事項の文字列になります。

役に立ちましたか?

解決

このiOS6.1ラマ"をコンセプトとした7:

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
}

または迅速な作業を迅速に4.1にiOS11)

let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

したい場合は支援のためのiOS6.1合には:

textview.scrollEnabled = NO;

他のヒント

この不良などにより、iOS7以上

が、実際には非常に簡単に行うにサイズ変更の UITextView その正しい高さです。でをベースに制御を行っています。 UITextView contentSize.

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

気をつけなければいけないの注意が正しく設定していること contentSizeUITextView が追加されているビュー addSubview.前のことですが、 frame.size

これは動作しない場合は自動レイアウトします。自動レイアウトは、一般的なアプローチにも利用され sizeThatFits 方法を更新 constant 価値の高さに与えます。

CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];
heightConstraint.constant = sizeThatShouldFitTheContent.height;

heightConstraint であるレイアウトの制約で、通常は設定を介してIBOutletによるリンクには高さ制約で作成した絵コンテ.


るだけで追加この素晴らしい答えは、2014年までご連絡ください。

[self.textView sizeToFit];

差がある行動を iPhone6+

enter image description here

の6+のみなさ5s6)で追加"もうひとつの空白線"のUITextView.の"RLソリューション"の修正にこの完璧:

CGRect _f = self.mainPostText.frame;
_f.size.height = self.mainPostText.contentSize.height;
self.mainPostText.frame = _f;

を固定するので、"追加ライン"問題の6+.

作動的にサイジング UITextViewUITableViewCell, また、以下の組み合わせで動作Xcode6のiOS8SDK

  • を追加 UITextViewUITableViewCell を制約し、左右に
  • の設定 UITextView's scrollEnabledNO.とにスクロール機能を有効にすると、フレームの UITextView 独立したコンテンツのサイズ、スクロール障害者の関係が下記の数式で表せます。
  • 場合はテーブルを使用して独自のデフォルトの行の高さは44でを自動算出する行の高さが変更された場合、それぞれのデフォルトの行の高さになっても、他のものが必要になる場合があり手動スイッチの自動計算の行の高さ viewDidLoad:

    tableView.estimatedRowHeight = 150;
    tableView.rowHeight = UITableViewAutomaticDimension;
    

読み込み専用に動的にサイジング UITextViews,それだけです。だがユーザーがサービス毎に使い分けテキストの編集をお UITextView, また:

  • の実施を textViewDidChange: の方法 UITextViewDelegate プロトコルをお伝え下さい tableView を塗り替え自体にテキストを編集:

    - (void)textViewDidChange:(UITextView *)textView;
    {
        [tableView beginUpdates];
        [tableView endUpdates];
    }
    
  • と設定するのを忘れずに、 UITextView 委譲のどこかに、 Storyboard または tableView:cellForRowAtIndexPath:

Swift:

textView.sizeToFit()

非常に働きやすいソリューションコードと絵コンテを両立。

コード

textView.scrollEnabled = false

による絵コンテ

チェックを外 スクロールする

enter image description here

なものとは別のものです。

私のものに限)の経験

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

いつの改行文字で終わる多くの短縮 CGSize で実際に必要です。

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

いを尊重し、改行.

また、テキストな描画される最 UITextView.私のコードを設定します新しい高さの UITextView 24ピクセル以上の高さによって返される sizeOfFont ます。

にiOS6を確認することができる contentSize 物件のUITextViewた後で、そのまま設定します。にiOS7このなくなります。を復元する場合は、復元するこの挙動をiOS7、以下のコードをサブクラスのUITextView.

- (void)setText:(NSString *)text
{
    [super setText:text];

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];
        UIEdgeInsets inset = self.textContainerInset;
        self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;
    }
}

今後の適切なソリューションのページ下部にある場合人の勇者(または誰な)を読み取ることができた。

こちらはgitHubレポる人になりたい読みすべてのテキスト: resizableTextView

この作品iOs7(やったと思いますiOs8)autolayout.必要な数字のマジックを無効にするレイアウトやれるというような。 短優雅な解決策です。

と思い、すべての制約関連のコードがあります。 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います。

簡単にアニメーションの変更を 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];

ただ [textView sizeThatFits:textView.bounds] ?

編集:sizeThatFitsサイズを返しまない実際のサイズの変更、コンポーネントに対するさんそしたい場合、または [textView sizeToFit] りだけを見ているわけです。いずれの場合も、わからない場合でフィットのコンテンツのようにしたいで最初のものについてです。

もう一つの方法は、サイズ、特定の文字列を取り上げてその利用 NSString 方法:

-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

このサイズを返します矩形の指定された文字列を、指定された揺るぎないコミットメントです。Passサイズをもとに、ご希望の幅および最大高されるまでの高さを返に合わせています。がバージョンをまとめて見ることができる指定を行モードもございます

を利用できます、返されるサイズ変更のサイズのビューを作成できます。

ない場合は、 UITextView ハンディ(例えば、サイズ表示細胞としての計算のサイズを測定し、文字列、計8つのptのパディングのサイズ UITextView.例えば、ご希望の幅のテキストビューしたのに対応する高さ:

NSString * string = ...;
CGFloat textViewWidth = ...;
UIFont * font = ...;

CGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);
size.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;

ここでは、各8では、この会計処理の違いはエ100000って非常に大きな最大サイズです。

実際にはたいということはキャリー font.leading の高さこの追加に空白を以下のテキストには、より良く見える場合があり視覚的に重制御の直下にテキスト。

以下のことに十分:

  1. とを覚えておいてくださいの設定 スクロール可能NOUITextView:

enter image description here

  1. 正しく設定されています自動レイアウトの制約

さて、私にとっての利用 UITableViewAutomaticDimension.

していきます。

  1. セット高さ制限のUITextView.enter image description here

2.をIBOutletその高さに与えます。

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;

3.設定するのを忘れずに委譲のごtextview.

4.

-(void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));
    [UIView animateWithDuration:0.2 animations:^{
                  _txtheightconstraints.constant=newFrame.size.height;
    }];

}

更新してくださの制約のようになります:)

複合マイク-マクマスターの回答するためには、次のように:

[myTextView setDelegate: self];

...

- (void)textViewDidChange:(UITextView *)textView {
  if (myTextView == textView) {
     // it changed.  Do resizing here.
  }
}

私ためのリサイズの高さにより、テキストフィールドにテキストの中でもレベル以下での高さのテキストフィールド!こちらのコードです。

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
NSString *str = @"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
_textView.text = str;

[self.view addSubview:_textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];
lbl.text = @"Hello!";
[self.view addSubview:lbl];

男用autolayoutをごsizetofitていない、それを確認してください幅を制約します。まった場合の幅を制約の高さまですることができなくなります。

を使用する必要がなく、その他のAPIとなります。で行う全ての課題です。

[_textView sizeToFit];

ここだけでした関心の高さ、幅を固定したの幅を制約のTextViewに絵コンテ.

この動的なコンテンツからのサービス

ことを期待しが..

はじめiOS8の利用が可能で、自動レイアウトの特徴はUITableViewの自動リサイズ、UITextViewのないカスタムコードです。し出していただきありがとうございプロジェクト github ることを示してこの行動が、ここでのキー:

  1. のUITextViewなスクロールを無効にできないプログラムを通じてのビルダを構築します。なサイズの変更にスクロールする場合は有効で、スクロールでき、大きます。
  2. にviewDidLoadのUITableViewControllerなく、また設定値estimatedRowHeight設定し、 rowHeightUITableViewAutomaticDimension.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = self.tableView.rowHeight;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}
  1. のプロジェクトの展開対象物のiOS8以上に高めていきます。

この働く場してしまい、申し訳なく思いテキスト UITextView fit特定の地域:

// The text must already be added to the subview, or contentviewsize will be wrong.

- (void) reduceFontToFit: (UITextView *)tv {
    UIFont *font = tv.font;
    double pointSize = font.pointSize;

    while (tv.contentSize.height > tv.frame.size.height && pointSize > 7.0) {
        pointSize -= 1.0;
        UIFont *newFont = [UIFont fontWithName:font.fontName size:pointSize];
        tv.font = newFont;
    }
    if (pointSize != font.pointSize)
        NSLog(@"font down to %.1f from %.1f", pointSize, tv.font.pointSize);
}

ここでは迅速な版@jhibberd

    let cell:MsgTableViewCell! = self.tableView.dequeueReusableCellWithIdentifier("MsgTableViewCell", forIndexPath: indexPath) as? MsgTableViewCell
    cell.msgText.text = self.items[indexPath.row]
    var fixedWidth:CGFloat = cell.msgText.frame.size.width
    var size:CGSize = CGSize(width: fixedWidth,height: CGFloat.max)
    var newSize:CGSize = cell.msgText.sizeThatFits(size)
    var newFrame:CGRect = cell.msgText.frame;
    newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height);
    cell.msgText.frame = newFrame
    cell.msgText.frame.size = newSize        
    return cell

を見直したすべての回答は、すべてを固定幅を調整だけます。ご希望の場合は調整も幅できる非常に容易に利用方法:

ように設定する場合はテキストには、設定スクロールを無効に

textView.isScrollEnabled = false

さらに委譲方法 func textViewDidChange(_ textView: UITextView) 追加のコード:

func textViewDidChange(_ textView: UITextView) {
    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    textView.frame = CGRect(origin: textView.frame.origin, size: newSize)
}

出力:

enter image description here

enter image description here

スクロールを無効化

追加constaints

追加テキスト

[yourTextView setText:@"your text"];
[yourTextView layoutIfNeeded];

ご利用の場合 UIScrollView すすも

[yourScrollView layoutIfNeeded];

-(void)viewDidAppear:(BOOL)animated{
    CGRect contentRect = CGRectZero;

    for (UIView *view in self.yourScrollView.subviews) {
         contentRect = CGRectUnion(contentRect, view.frame);
    }
    self.yourScrollView.contentSize = contentRect.size;
}

IOS7.0ではなく、設定の frame.size.heightcontentSize.height (現在は何も行いません)を使用 [textView sizeToFit].

この質問.

こういう事が決められません:

- (void)textViewDidChange:(UITextView *)textView {
  CGSize textSize = textview.contentSize;
  if (textSize != textView.frame.size)
      textView.frame.size = textSize;
}

場合その他、このソリューション作品、1"Ronnie Liew"+4"user63934"(自分のテキストから到着したウェブサービス:注1000(何もできるのも大きな"私の場合")

UIFont *fontNormal = [UIFont fontWithName:FONTNAME size:FONTSIZE];

NSString *dealDescription = [client objectForKey:@"description"];

//4
CGSize textSize = [dealDescription sizeWithFont:fontNormal constrainedToSize:CGSizeMake(containerUIView.frame.size.width, 1000)];

CGRect dealDescRect = CGRectMake(10, 300, containerUIView.frame.size.width, textSize.height);

UITextView *dealDesc = [[[UITextView alloc] initWithFrame:dealDescRect] autorelease];

dealDesc.text = dealDescription;
//add the subview to the container
[containerUIView addSubview:dealDesc];

//1) after adding the view
CGRect frame = dealDesc.frame;
frame.size.height = dealDesc.contentSize.height;
dealDesc.frame = frame;

ことになるが---乾杯

最良の方法を見つける再サイズの高さをUITextViewに応じてのサイズです。

CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]
                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX)];

ことができま

CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]
                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];

したい方のtextview実際に移動維持により、下線の位置

CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;

if(frame.size.height > textView.frame.size.height){
    CGFloat diff = frame.size.height - textView.frame.size.height;
    textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
    CGFloat diff = textView.frame.size.height - frame.size.height;
    textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}

唯一のコードで動作するものを使用してSizeToFitンなどのjhibberd答え上がんを迎えないと通話で ViewDidAppear またはワイヤーでUITextViewテキストを変更します。

ベニキータがたかったのは以下のソリューションに迅速に動作するiOS8autolayout:

    descriptionTxt.scrollEnabled = false
    descriptionTxt.text = yourText

    var contentSize = descriptionTxt.sizeThatFits(CGSizeMake(descriptionTxt.frame.size.width, CGFloat.max))
    for c in descriptionTxt.constraints() {
        if c.isKindOfClass(NSLayoutConstraint) {
            var constraint = c as! NSLayoutConstraint
            if constraint.firstAttribute == NSLayoutAttribute.Height {
                constraint.constant = contentSize.height
                break
            }
        }
    }

迅速に回答:次のコードを計算の高さのtextView.

                let maximumLabelSize = CGSize(width: Double(textView.frame.size.width-100.0), height: DBL_MAX)
                let options = NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin
                let attribute = [NSFontAttributeName: textView.font!]
                let str = NSString(string: message)
                let labelBounds = str.boundingRectWithSize(maximumLabelSize,
                    options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                    attributes: attribute,
                    context: nil)
                let myTextHeight = CGFloat(ceilf(Float(labelBounds.height)))

現在の設定ができます高のtextViewに myTextHeight

ここではその答えが必要な場合はサイズ変更 textViewtableViewCell ダイナミックに staticTableView

[https://stackoverflow.com/a/43137182/5360675][1]

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top