문제

크기를 조정하는 좋은 방법이 있나요? UITextView 내용에 맞게?예를 들어 내가 가지고 있다고 해봐 UITextView 한 줄의 텍스트가 포함되어 있습니다.

"Hello world"

그런 다음 다른 텍스트 줄을 추가합니다.

"Goodbye world"

코코아 터치에 좋은 방법이 있나요? rect 그러면 그에 따라 상위 뷰를 조정할 수 있도록 텍스트 뷰의 모든 줄이 유지됩니까?

또 다른 예로, 캘린더 애플리케이션의 이벤트에 대한 메모 필드를 살펴보세요. 셀(및 UITextView 포함)은 메모 문자열의 모든 텍스트 줄을 포함하도록 확장됩니다.

도움이 되었습니까?

해결책

이는 iOS 6.1과 iOS 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;
}

또는 Swift에서(iOS 11의 Swift 4.1에서 작동)

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)

iOS 6.1에 대한 지원을 원할 경우 다음도 수행해야 합니다.

textview.scrollEnabled = NO;

다른 팁

iOS 7 이상에서는 더 이상 작동하지 않습니다.

실제로 크기를 조정하는 매우 쉬운 방법이 있습니다. UITextView 내용의 정확한 높이로.이는 다음을 사용하여 수행할 수 있습니다. UITextView contentSize.

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

한 가지 주의할 점은 올바른 contentSize 만 가능합니다 ~ 후에 그만큼 UITextView 다음과 같이 뷰에 추가되었습니다. addSubview.그 전에는 다음과 같습니다. frame.size

자동 레이아웃이 켜져 있으면 작동하지 않습니다.자동 레이아웃의 일반적인 접근 방식은 sizeThatFits 메서드를 업데이트하고 constant 높이 제한에 대한 값입니다.

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

heightConstraint 스토리보드에서 생성된 높이 제약 조건에 속성을 연결하여 일반적으로 IBOutlet을 통해 설정하는 레이아웃 제약 조건입니다.


이 놀라운 답변(2014년)에 추가하자면 다음과 같습니다.

[self.textView sizeToFit];

행동에는 차이가 있다 아이폰6+ 오직:

enter image description here

6+만(5s 또는 6이 아닌) 경우 UITextView에 "빈 줄 하나 더"를 추가합니다."RL 솔루션"은 이 문제를 완벽하게 해결합니다.

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

6+에서 "추가 줄" 문제를 해결합니다.

동적으로 크기를 조정하려면 UITextView 안에 UITableViewCell, iOS 8 SDK가 있는 Xcode 6에서 다음 조합이 작동하는 것을 발견했습니다.

  • 을 추가하다 UITextViewUITableViewCell 측면으로 제한합니다.
  • 설정 UITextView'에스 scrollEnabled 재산 NO.스크롤이 활성화되면 UITextView 콘텐츠 크기와 무관하지만 스크롤이 비활성화되면 둘 사이에 관계가 있습니다.
  • 테이블이 원래 기본 행 높이 44를 사용하는 경우 행 높이가 자동으로 계산되지만 기본 행 높이를 다른 것으로 변경한 경우 행 높이 자동 계산을 수동으로 켜야 할 수도 있습니다. viewDidLoad:

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

읽기 전용 동적 크기 조정의 경우 UITextView응, 그게 다야.사용자가 텍스트를 편집할 수 있도록 허용하는 경우 UITextView, 다음도 수행해야 합니다.

  • 구현 textViewDidChange: 의 방법 UITextViewDelegate 프로토콜을 지정하고 tableView 텍스트가 편집될 때마다 자체적으로 다시 칠하려면 다음을 수행하십시오.

    - (void)textViewDidChange:(UITextView *)textView;
    {
        [tableView beginUpdates];
        [tableView endUpdates];
    }
    
  • 그리고 설정하는 것을 잊지 마세요 UITextView 어딘가에 위임하십시오. Storyboard 또는 tableView:cellForRowAtIndexPath:

빠른 :

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 저장소는 다음과 같습니다. 크기 조정이 가능한텍스트 보기

이는 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];

이제 우리 수업은 다음과 같습니다:

ResizingTextView.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];
}

예쁘고 깨끗하죠?그리고 당신은 당신의 컴퓨터에서 해당 코드를 다룰 필요가 없습니다. 컨트롤러!

하지만 기다려! 애니메이션이 없습니다!

변경 사항을 쉽게 애니메이션으로 만들 수 있습니다. 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

주어진 글꼴과 주어진 문자열에 맞는 직사각형의 크기를 반환합니다.원하는 너비와 최대 높이의 크기를 전달하면 텍스트에 맞게 반환된 높이를 확인할 수 있습니다.줄바꿈 모드를 지정할 수 있는 버전도 있습니다.

그런 다음 반환된 크기를 사용하여 뷰의 크기를 맞게 변경할 수 있습니다.

당신이 가지고 있지 않은 경우 UITextView 편리합니다(예: 테이블 뷰 셀의 크기를 조정하는 경우). 문자열을 측정하여 크기를 계산한 다음 각 측면의 패딩 8pt를 계산해야 합니다. 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은 패딩된 4개의 가장자리 중 하나를 차지하며 100000은 매우 큰 최대 크기 역할을 합니다.

실제로는 추가 항목을 추가할 수도 있습니다. font.leading 높이까지;이렇게 하면 텍스트 아래에 빈 줄이 추가되며, 텍스트 보기 바로 아래에 시각적으로 무거운 컨트롤이 있는 경우 더 보기 좋을 수 있습니다.

다음 사항이면 충분합니다.

  1. 설정하는 것만 기억하세요 스크롤 가능 에게 아니요 당신을 위해 UITextView:

enter image description here

  1. 자동 레이아웃 제약 조건을 올바르게 설정하세요.

당신은 사용할 수도 있습니다 UITableViewAutomaticDimension.

제약 조건을 통해 이를 수행할 수 있습니다.

  1. UITextView에 대한 높이 제약 조건을 설정합니다.enter image description here

2. 해당 높이 제약에 대한 IBOutlet을 생성합니다.

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

3. 텍스트 뷰에 대리자를 설정하는 것을 잊지 마십시오.

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;
    }];

}

그런 다음 제약 조건을 다음과 같이 업데이트하십시오. :)

Mike McMaster의 답변과 결합하여 다음과 같은 작업을 수행할 수 있습니다.

[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];

자동 레이아웃을 사용하고 있는데 크기에 맞게 작동하지 않는 경우 너비 제한을 한 번 확인하십시오.너비 제한을 놓친 경우 높이가 정확해집니다.

다른 API를 사용할 필요가 없습니다.한 줄만 있으면 모든 문제가 해결됩니다.

[_textView sizeToFit];

여기서는 높이에만 관심을 갖고 너비를 고정한 상태로 유지했으며 스토리보드에서 TextView의 너비 제한을 놓쳤습니다.

그리고 이는 서비스의 동적 콘텐츠를 표시하는 것이었습니다.

이것이 도움이 되기를 바랍니다..

iOS 8부터는 UITableView의 자동 레이아웃 기능을 사용하여 사용자 정의 코드 없이 UITextView의 크기를 자동으로 조정할 수 있습니다.프로젝트를 넣었어요 깃허브 이는 실제로 이를 보여주지만 여기에 핵심이 있습니다.

  1. UITextView는 프로그래밍 방식으로 또는 인터페이스 빌더를 통해 스크롤링을 비활성화해야 합니다.스크롤을 사용하면 더 큰 콘텐츠를 볼 수 있으므로 스크롤이 활성화된 경우 크기가 조정되지 않습니다.
  2. UITableViewController의 viewDidLoad에서 estimateRowHeight 값을 설정한 다음 rowHeight 에게 UITableViewAutomaticDimension.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = self.tableView.rowHeight;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}
  1. 프로젝트 배포 대상은 iOS 8 이상이어야 합니다.

이것은 내가 텍스트를 작성해야 할 때 잘 작동했습니다. UITextView 특정 영역에 맞게:

// 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

스크롤 비활성화

제약 조건 추가

그리고 텍스트를 추가하세요

[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;
}

iOS 7.0의 경우 frame.size.height ~로 contentSize.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];

텍스트 뷰가 실제로 위로 이동하고 최종 위치를 유지하기를 원하는 사람들을 위해

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);
}

작동하는 유일한 코드는 위의 jhibberd 답변에서와 같이 'SizeToFit'을 사용하는 코드이지만 실제로 호출하지 않으면 선택되지 않습니다. 보기Did나타났음 또는 UITextView 텍스트 변경 이벤트에 연결하세요.

Nikita Took의 답변을 바탕으로 자동 레이아웃을 사용하여 iOS 8에서 작동하는 Swift의 다음 솔루션을 찾았습니다.

    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

크기 조정이 필요한 경우 답변은 다음과 같습니다. textView 그리고 tableViewCell 동적으로 staticTableView

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top