Search code examples
iosswiftxcodeautolayoutuitextview

UITextView placement acting weird with autolayout


I have a UITextView that is acting really weird why I try to constrain it with autolayout. The background will be placed right, but the text within is out of place. I tried to create an UIView, and then add it to the UIView instead, but the problem still persists.

Here is the UITextView and UIView declarations

let noteTextView: UITextView =
{
    let tv = UITextView()
    tv.textColor = UIColor.white
    tv.backgroundColor = UIColor.clear
    tv.font = UIFont.systemFont(ofSize: 16)
    tv.isEditable = false
    tv.isUserInteractionEnabled = true

    return tv
}()

let backgroundView: UIView =
{
    let view = UIView()
    view.backgroundColor = UIColor.rgb(red: 156, green: 44, blue: 252)

    return view
}()

And here is the constraints (using an extension called anchor)

    view.addSubview(backgroundView)
    backgroundView.addSubview(noteTextView)

    backgroundView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 65, paddingLeft: 0, paddingRight: 0, paddingBottom: 0, width: 0, height: 80)

    noteTextView.anchor(top: backgroundView.topAnchor, left: backgroundView.leftAnchor, bottom: backgroundView.bottomAnchor, right: backgroundView.rightAnchor, paddingTop: 2, paddingLeft: 5, paddingRight: 5, paddingBottom: 2, width: 0, height: 0)

Here is a video to demonstrate the problem: https://streamable.com/y8v70

Note: When I just added the UITextView to the view (without the UIVIew) the exact same thing happened.


Solution

  • Disable automaticallyAdjustsScrollViewInsets in viewDidLoad

    self.automaticallyAdjustsScrollViewInsets = false
    

    Try also:

    textView.textContainerInset = UIEdgeInsetsZero;  
    textView.textContainer.lineFragmentPadding = 0;
    

    May this help.