skip to Main Content

Planning to use the same text view in multiple places in the app so planning to create text view component without xib/Storyboard so that the same can be reuse in multiple places.

I’m a junior developer how can we create a text view component programmatically which can display two lines of text as shows in below screenshot.

screenshot

Created a class of text view and trying to add text in it. please advice/suggest the flow to implement this.

@IBDesignable public class HyperLinksTextView: UITextView {
required public init?(coder: NSCoder) {
    super.init(coder: coder)
    self.backgroundColor = .clear
    createTextView()
}

func createTextView() {

}

}

2

Answers


  1. txtView.textContainer.maximumNumberOfLines = 2
    

    try this 🙂

    Login or Signup to reply.
  2. If you need to display static text with no editing features and no selection features, you should use a UILabel.

    If you need selection or editing, use UITextView.

    For Creating UILabel Subclass for using everywhere:

    import UIKit
    class MyLabel: UILabel {
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeLabel()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeLabel()
    }
    
    func initializeLabel() {
    
        self.textAlignment = .left
        self.font = UIFont(name: "Halvetica", size: 17) // your customs
        self.textColor = .black
        self.numberOfLines = 2
        //other customisations
    }
    }
    

    And here’s how you use it in your View Controller:

    import UIKit

    class ViewController: UIViewController {

     var myLabel: MyLabel()
    
     override func viewDidLoad() {
          super.viewDidLoad()
    
          myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
          self.view.addSubView(myLabel)
     }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search