Search code examples
swiftuitextviewbackground-imageswift4

UITextView background image is scrolling for multiple lines


I have created extension for UITextView, where I set image to the textview using below code.

let backgroundImage = UIImageView(frame: ....)
backgroundImage.image = UIImage(named: "textarea.png")
self.addSubview(backgroundImage)
self.sendSubview(toBack: backgroundImage)

At start it looks fine as showing below image (left side), however as I add multi-line text, image also starts scrolling (right side), which is incorrect.

enter image description here

Any idea how to make image fixed as it is?


Solution

  • Below is what I did

    let backgroundImage = UIImageView(frame:  ....)
    backgroundImage.image = UIImage(named: "textarea.png")
    mainView.insertSubview(backgroundImage, belowSubview: self)
    

    mainView is nothing but the main view (self.view) of view controller.

    This is like we are not going to add backgroundImage in the subview of textview, instead we will be adding in the mainview (self.view).