program tip

UITextView는 텍스트의 하단 또는 중간에서 시작합니다.

radiobox 2020. 10. 20. 07:30
반응형

UITextView는 텍스트의 하단 또는 중간에서 시작합니다.


나는 그것을 바로 잡을 것이다. 나는이 UItextView내보기에 배치 스크롤에 대한 요구가 참조하는 때 모든 텍스트 때로는 텍스트의 중간에 텍스트 뷰를 시작하고 텍스트의 맨 아래 다른 시간에 (많은 텍스트는 텍스트 뷰에 존재하는 경우).

여기에 이미지 설명 입력

textView에서 편집이 활성화되지 않았습니다. 항상 textView를 맨 위에서 시작하도록 강제하는 방법이 필요합니다. 다른 사람들이 콘텐츠 오프셋을 사용하는 것과 비슷한 질문을 보았지만 어떻게 작동하는지 또는 여기에 적용 할 수 있는지는 잘 모릅니다.

당신의 도움을 주셔서 감사합니다.


그것은 나를 위해 속임수를 썼습니다!

목표 C :

[self.textView scrollRangeToVisible:NSMakeRange(0, 0)];

빠른:

self.textView.scrollRangeToVisible(NSMakeRange(0, 0))

Swift 2 (대체 솔루션)

이 재정의 메서드를 ViewController에 추가하십시오.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    textView.setContentOffset(CGPointZero, animated: false)
}

Swift 3 & 4 (구문 편집)

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()

  textView.contentOffset = .zero
}

위의 모든 답변이 저에게 효과적이지 않았습니다. 그러나 비밀은 다음과 같이 viewDidLayoutSubviews 재정의 내에서 솔루션을 구현하는 것으로 밝혀졌습니다.

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()

  welcomeText.contentOffset = .zero
}

HTH :)


Swift 2에서

이것을 사용하여 textView를 맨 위에서 시작할 수 있습니다.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    myTextView.setContentOffset(CGPointZero, animated: false)
}

Swift 2로 Xcode 7.2에서 작동 확인


아래 코드를 시도하십시오-

if ( [self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]){
     self.automaticallyAdjustsScrollViewInsets = NO;         
}

또는 StoryBoard에서이 속성을 설정할 수도 있습니다.

ViewController를 선택한 다음 속성 검사기를 선택하십시오 Adjust Scroll View Insets.


Swift> 2.2의 경우 작동하는 단일 답변이 없기 때문에 위의 방법을 사용하여 iOS 8 및 iOS 9에 문제가 있었으므로 여기에 두 가지 모두에서 작동하도록 한 작업이 있습니다.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    if #available(iOS 9.0, *) {
        textView.scrollEnabled = false
    }

    self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    if #available(iOS 9.0, *) {
        textView.scrollEnabled = true
    }
}

UINavigationBar의 translucent속성을 NO다음과 같이 업데이트하십시오 .

self.navigationController.navigationBar.translucent = NO;

이렇게하면 탐색 표시 줄과 상태 표시 줄 아래에있는보기가 수정됩니다.

탐색 모음을 표시하고 숨겨야하는 경우 아래 코드를 사용하여 viewDidLoad

 if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7 specific

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


많은 테스트를 통해 UITextView가 처음부터 표시되도록 viewWillLayoutSubviews () 함수에 아래를 추가해야 함을 발견했습니다.

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()            
    textViewTerms.scrollRangeToVisible(NSMakeRange(0, 0))
}

UITextView스크롤링은 많은 사람들에게 문제가되는 것 같습니다. 여기에 대한 답변 (특히 this )과 Apple Developer 문서에서 내 자신의 재치를 사용하여 수집 하면 여기에 적합한 솔루션이 있습니다. 필요에 맞게 코드를 수정할 수 있습니다.

내 사용 사례는 다음과 같습니다. 동일한 내용 UITextView이 다른 용도로 사용되어 다른 상황에서 다양한 콘텐츠를 표시합니다. 내가 원하는 것은 콘텐츠가 변경되면 이전 스크롤 위치가 복원되거나 때때로 끝까지 스크롤된다는 것입니다. 이 작업이 끝나면 너무 많은 애니메이션을 원하지 않습니다. 특히 모든 텍스트가 새로운 것처럼 뷰가 애니메이션되는 것을 원하지 않습니다. 이 솔루션은 먼저 애니메이션없이 이전 스크롤 위치를 복원 한 다음 원하는 경우 애니메이션 끝으로 스크롤합니다.

해야 할 일은 (또는 할 있다고 말해야 하나요) UITextView를 다음과 같이 확장하는 것입니다.

extension UITextView {
  func setText(text: String, storedOffset: CGPoint, scrollToEnd: Bool) {
    self.text = text
    let delayInSeconds = 0.001
    let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
    dispatch_after(popTime, dispatch_get_main_queue(), {
      self.setContentOffset(storedOffset, animated: false)
      if scrollToEnd && !text.isEmpty {
        let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
        dispatch_after(popTime, dispatch_get_main_queue(), {
          self.scrollRangeToVisible(NSMakeRange(text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) - 1, 0))
        })
      }
    })
  }
}

What this does is it updates the text, then uses a stored value of the UITextView.contentOffset property (or anything you pass as a parameter), and sets the offset of the view accordingly. If desired, after this, it scrolls to the end of the new, potentially changed content.

I'm new to iOS programming and I don't know why it works so well it does, if someone has some information on this it would be nice to know. Also the approach may not be perfect so I'm open to improvement ideas as well.

And of course thanks to NixonsBack for posting the answer behind the link above.

My first post :), cheers!


Xcode 7.2 7c68; IOS 9.1

My ViewController which contains UITextView is complicated, and changed a lot during the project (IDE version changed maybe 2~3 times too).

I've tried all above solutions, if you encounter the same issue, be PATIENT.

There are three possible 'secret codes' to solve:

  1. textView.scrollEnabled = false //then set text textView.scrollEnabled = true
  2. textView.scrollRangeToVisible(NSMakeRange(0, 0))
  3. textView.setContentOffset(CGPointZero, animated: false)

And there are two places you can put those codes in:

  1. viewDidLoad()
  2. viewDidLayoutSubviews()

Combine them, you'll get 3*2=6 solutions, the correct combination depends on how complicated you ViewController is (Believe me, after delete just a view above textView, I need to find a new combination).

And I found that:

When put 'secret codes' in viewDidLayoutSubviews(), but textView.text = someStrings in viewDidLoad(), the content in textView will 'shake' sometimes. So, put them in the same place.

Last word: try ALL combinations, this is how I solve this stupid bug more than three times during two months.


Put this one line of code in ViewDidLoad

self.automaticallyAdjustsScrollViewInsets = false

The following code should give you effect you want.

[self.scrollView setContentOffset:CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];

You'll need to replace "self.scrollView" with the name of your scroll view. You should put this code in after you've set the text of the scroll view.


This worked for me:

 override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    textView.scrollRectToVisible(CGRect(origin: CGPointZero, size: CGSizeMake(1.0, 1.0)), animated: false)

}

This worked for me with Xcode 8.3.3:

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self.txtQuestion scrollRangeToVisible:NSMakeRange(0, 0)];
}

Create an outlet for your UITextView in the ViewController.swift file. In the ViewDidLoad section put the following:

Swift:

self.textView.contentOffset.y = 0

I have tried:

self.textView.scrollRangeToVisible(NSMakeRange(0, 0))

I translated zeeple's answer to MonoTouch/Xamarin (C#).

public override void ViewDidLayoutSubviews()
{
    base.ViewDidLayoutSubviews();
    myForm.SetContentOffset(new CoreGraphics.CGPoint(0,0), animated: false);
}

I had to implement two answers here to get my view working as I want:

From Juan David Cruz Serrano:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    textView.setContentOffset(CGPoint.zero, animated: false)
}

And from Murat Yasar:

automaticallyAdjustsScrollViewInsets = false

This gave a UITextView that loads with the scroll at the very top and where the insets are not changed once scrolling starts. Very strange that this is not the default behaviour.


To force the textView to start at the top every time, use the following code:

Swift 4.2:

override func viewDidLayoutSubviews() {
    textView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
}

Objective-C:

- (void)viewDidLayoutSubviews {
    [self.yourTextView setContentOffset:CGPointZero animated:NO];
}

Swift 4.2 & Swift 5

set content offset both before and after setting the text. (on the main Thread)

let animation = false //or whatever you want
self.mainTextView.setContentOffset(.zero, animated: animation)
self.mainTextView.attributedText = YOUR_ATTRIBUTED_TEXT
self.mainTextView.setContentOffset(.zero, animated: animation)

In my case I was loading a textView in a Custom tableview cell. Below is what I did to make sure the text in a textview loads at the top of the text in my textview in my custom cell.

1.) In storyboard, set the textview ScrollEnabled = false by unchecking the button.

2.) You set the isScrollEnabled to true on the textview after the view loads. I set mine in a small delay like below:

override func awakeFromNib() {
    super.awakeFromNib()

let when = DispatchTime.now() + 1
      DispatchQueue.main.asyncAfter(deadline: when){
        self.textView.isScrollEnabled = true
     }

}

Regardless, if you are in my situation or not, try setting scrollEnabled to false and then when the view loads, set scrollEnabled to true.

참고URL : https://stackoverflow.com/questions/27622437/uitextview-starts-at-bottom-or-middle-of-the-text

반응형