user979331
user979331

Reputation: 11851

UITextView does not show text

I have created a UITextView class and I'm adding the UITextView on touch. The UITextView appears, however the set text does not appear and when I touch the UITextView the keyboard will appear, but when I start writing text, it does not appear.

Here is my UITextView class:

import UIKit

class TextAnnotation: UITextView {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        self.text = "Text Field"
        self.textColor = UIColor.blackColor()
        self.userInteractionEnabled = true
        self.editable = true
        self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 200, height: 50)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

and here is how I am calling this class to add the UITextView on touch:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let textCenter = touches.first!.locationInView(view)
    let textView = TextAnnotation(frame: CGRect(x: textCenter.x, y: textCenter.y, width: 200, height: 50), textContainer: NSTextContainer())

    self.view.addSubview(textView)
}

How do I get the set text to appear and why is not showing when I start typing

Upvotes: 1

Views: 1030

Answers (1)

Evgeny Karkan
Evgeny Karkan

Reputation: 9612

Ok,touchesBegan function - is a bad place to initialise and add subview to superview, because it can be called many times.
I guess you have more than 1 instance of textView, and every new instance overlays previous one.

What can I suggest - is to replace textView initialisation and layout code to init or viewDidLoad etc. function, hide your textView, and on touch event - just show it.

Upvotes: 1

Related Questions