Home > Enterprise >  How to create TextView component which shows two lines of text in swift iOS
How to create TextView component which shows two lines of text in swift iOS

Time:11-23

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() {

}

}

CodePudding user response:

txtView.textContainer.maximumNumberOfLines = 2

try this :)

CodePudding user response:

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)
 }
}
  • Related