How to create multiple styles inside a TextView on iOS App?

iPhoneiOSMobile Development

To create multiple styles inside a textview we need to use attributed string. The text view in ios has a property attributedText which can be used to style the text inside a text view. We’ll see this with help of an example.

First, we’ll create an attribute

let attributeOne : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize: 16.0), NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : UIColor.blue]

Then we’ll create an attributed string with the attribute we created

let string = NSAttributedString(string: "Text for first Attribute", attributes: attributeOne)

Similarly, we’ll create another string with different attribute. Then we’ll initialize the text of textView with the attributed string.

Now the whole code should look like as shown below.

let tx = UITextView()
   tx.isScrollEnabled = true
   tx.isUserInteractionEnabled = true
   tx.frame = CGRect(x: 10, y: 25, width: self.view.frame.width, height: 100)
   let attributeOne : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize: 16.0), NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : UIColor.blue]
   let attributeTwo : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize: 20.0), NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : UIColor.red]
   let string = NSAttributedString(string: "Text for first Attribute", attributes: attributeOne)
   let string2 = NSAttributedString(string: "Text for first Attribute", attributes: attributeTwo)
   let finalAttributedString = NSMutableAttributedString()
   finalAttributedString.append(string)
   finalAttributedString.append(string2)
   tx.attributedText = finalAttributedString
   self.view.addSubview(tx)

When we’ll write up this code within our application, in viewDidLoad or viewWillAppear, this will create the textView as shown below.

raja
Published on 30-Jan-2019 10:10:41
Advertisements