Color only underline in Swift - swift

How do i change the color of my underline in a label? I want only the underline to change color, and not the entire text.
I have used this code to get the underline:
let underlineAttribute = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: "\(nearSavings[indexPath.row]) ,-", attributes: underlineAttribute)
cell.detailTextLabel?.attributedText = underlineAttributedString
But i cant find the code, to set the underline color. Anyone who can help?

Swift 4 Solution
You must use NSAttributedString with an array of attributes as [NSAttributedStringKey : Any].
Sample code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Colored Underline Label
let labelString = "Underline Label"
let textColor: UIColor = .blue
let underLineColor: UIColor = .red
let underLineStyle = NSUnderlineStyle.styleSingle.rawValue
let labelAtributes:[NSAttributedStringKey : Any] = [
NSAttributedStringKey.foregroundColor: textColor,
NSAttributedStringKey.underlineStyle: underLineStyle,
NSAttributedStringKey.underlineColor: underLineColor
]
let underlineAttributedString = NSAttributedString(string: labelString,
attributes: labelAtributes)
myLabel.attributedText = underlineAttributedString
}
}

Another solution could be to add a single line border under the label, that acts as an underline.
Get reference to the label
#IBOutlet weak var myLabel: UILabel!
Add the border under the label
let labelSize = myLabel.frame.size
let border = CALayer()
let w = CGFloat(2.0)
border.borderColor = UIColor.yellow.cgColor // <--- Here the underline color
border.frame = CGRect(x: 0, y: labelSize.height - w, width: labelSize.width, height: labelSize.height)
border.borderWidth = w
myLabel.layer.addSublayer(border)
myLabel.layer.masksToBounds = true
Note: with this workaround you underline the whole label. If you need to partially undlerline the text this solution is not appropiate

Swift 5 Solution
class UnderlinedLabel: UILabel {
override var text: String? {
didSet {
guard let text = text else { return }
let textColor: UIColor = .black
let underLineColor: UIColor = .lightGray
let underLineStyle = NSUnderlineStyle.single.rawValue
let labelAtributes:[NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.underlineStyle: underLineStyle,
NSAttributedString.Key.underlineColor: underLineColor
]
self.attributedText = NSAttributedString(string: text, attributes: labelAtributes)
}
}
}
Usage:
Just give class UnderlinedLabel to your label in the storyboard

The NSAttributedStringKey.underlineColor attribute does what you want:
let underlineAttributes = [
NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
NSAttributedStringKey.underlineColor: UIColor.orange
] as [NSAttributedStringKey : Any]
let underlineAttributedString = NSAttributedString(string: "Test", attributes: underlineAttributes)
This will set the underline color to orange whereas the text color will remain black.

Related

TextAlignmentStyle .natural doesn't work with SwiftUI

I need my text to change depend on text language not depend on App language
if it's RTL language like Arabic the text alignment should be RTL
if it's LTR language like English the text alignment should be LTR
I tried to import UILabel from UIKit because SwiftUI doesn't have .natural and .justified
like this
struct LabelAlignment: UIViewRepresentable {
var text: String
var textAlignmentStyle : TextAlignmentStyle
var width: CGFloat
var fontSize: CGFloat
var textColorName: String
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.textAlignment = NSTextAlignment(rawValue: textAlignmentStyle.rawValue)!
label.numberOfLines = 0
label.preferredMaxLayoutWidth = width
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentHuggingPriority(.required, for: .vertical)
label.textColor = UIColor(named: textColorName)
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
if let customFont = UIFont(name: "Almarai-Regular", size: fontSize) {
uiView.font = UIFontMetrics(forTextStyle: .headline).scaledFont(for: customFont)
uiView.adjustsFontForContentSizeCategory = true
} }
}
enum TextAlignmentStyle : Int{
case left = 0 ,center = 1 , right = 2 ,justified = 3 ,natural = 4
}
then I use it like this
HStack {
LabelAlignment(text: "My text" , textAlignmentStyle: . natural, width:UIScreen.main.bounds.width - 30, fontSize: 15, textColorName: "color3")
.padding(.horizontal,5)
.layoutPriority(1.0)
.foregroundColor(.textColor3)
.regularStyle(size: 15)
.padding([.bottom,.top], 8)
}
it working great with left ,center , right and justified
but it won't work with natural
As Adam mention
if you follow my old answer it won't work correctly if you change the App language
The correct way is
struct LabelAlignment: UIViewRepresentable {
var text: String
var width: CGFloat
var fontSize: CGFloat
var textColorName: String
var detectLangauge = ""
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
if detectLangauge == "Arabic" || detectLangauge == "العربية" {
label.textAlignment = .right
}else {
label.textAlignment = .left
}
label.numberOfLines = 0
label.preferredMaxLayoutWidth = width
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentHuggingPriority(.required, for: .vertical)
label.textColor = UIColor(named: textColorName)
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
if let customFont = UIFont(name: "Almarai-Regular", size: fontSize) {
uiView.font = UIFontMetrics(forTextStyle: .headline).scaledFont(for: customFont)
uiView.adjustsFontForContentSizeCategory = true
} }
}
Then use it like this
LabelAlignment(text: "My text", width: UIScreen.main.bounds.width - 30, fontSize: 15, textColorName: "color3",detectLangauge:detectLangauge)
it will work as .natural
Old answer :
I found a solution with pure SwiftUI
First you need to add these code
import Foundation
import NaturalLanguage
extension String {
func detectedLanguage() -> String? {
let recognizer = NLLanguageRecognizer()
recognizer.processString(self)
guard let languageCode = recognizer.dominantLanguage?.rawValue else { return nil }
let detectedLanguage = Locale.current.localizedString(forIdentifier: languageCode)
return detectedLanguage
}
}
then you need a #State value to save the result of detectedLanguage()
#State private var detectLangauge = ""
after that check the result of text by using
detectLangauge = "your text".detectedLanguage()
you can check your text language onApper() or after get result from API
then you need to add
Text("Your Text")
.multilineTextAlignment(detectLangauge == "Arabic" ? .trailing : .leading)

How to change a variable UITextView after clicking the button?

I create UITextView with a random tag and text, but it is created with one variable, is it possible to update the variable after creation UITextView (by clicking the add button)? Maybe add a random number to it, for example newText1, newText2.. etc.
So that the next UITextView is already created with a new variable?
P.S Sorry, if the question is silly, I just recently started to study Swift
#IBOutlet weak var addTextButton: UIButton!
#IBOutlet weak var StoriesView: UIView!
var newText = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func addTextButton(_ sender: Any) {
let maxNumber = 10000
let i = Int(arc4random_uniform(UInt32(maxNumber)))
newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
self.StoriesView.addSubview(newText)
newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.clear
newText.tag = i
newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true
newText.enablesReturnKeyAutomatically = true
newText.delegate = self
}
UPD:
let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
fontToolbar.barStyle = .default
fontToolbar.items = [
UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
fontToolbar.sizeToFit()
newText.inputAccessoryView = fontToolbar
in the toolBar above the keyboard I have buttons, here we change the color
#objc func redColor() {
newText.textColor = UIColor.red}
#objc func blueColor() {
newText.textColor = UIColor.blue}
#objc func greenColor() {
newText.textColor = UIColor.green}
So the color changes only in the newly created UITextView
On click of button, create a new texView and assign it a tag value. Once it is added, update the value of i to +1, so that every textView added has a new tag value.
var i = 1
var newText = UITextView()
#IBAction func addTextButton(_ sender: Any) {
newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
self.StoriesView.addSubview(newText)
newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.clear
newText.tag = i
newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true
newText.enablesReturnKeyAutomatically = true
newText.delegate = self
//increment i
i+=1
}
then you can access your textField via tag values like this:
if let textView = self.StoriesView.viewWithTag(i) as? UITextView {
// textView.text = "change it"
}
UPDATE:
Add textView Delegate method, and once a textView starts editing, change the newText value to the currently editing textView
class ViewController : UIViewController, UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
newText = textView
}
}
I have modified your code a bit to have new UITextView object with button click
import UIKit
class ScannerViewController: UIViewController, UITextViewDelegate {
#IBOutlet weak var StoriesView: UIView!
#IBOutlet weak var addTextButton: UIButton!
var yposition: CGFloat!
var textFieldTag: [Int]! = []
override func viewDidLoad() {
super.viewDidLoad()
yposition = 20
}
#IBAction func addTextButton(_ sender: Any) {
let xposition = self.StoriesView.frame.origin.x
let maxNumber = 10000
let i = Int(arc4random_uniform(UInt32(maxNumber)))
textFieldTag.append(i)
let newText = UITextView(frame: CGRect(x: xposition , y: yposition , width: 380, height: 40))
self.StoriesView.addSubview(newText)
newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.yellow
newText.tag = i
newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true
newText.enablesReturnKeyAutomatically = true
newText.delegate = self
yposition = yposition + 45
}
#IBAction func accessTextFields(_ sender: Any) {
//access all text fields
for tag in textFieldTag {
if let textField = self.StoriesView.viewWithTag(tag) as? UITextView {
//change properties here
textField.backgroundColor = .cyan
}
}
//access specific text fields
if let textField = self.StoriesView.viewWithTag(textFieldTag.first!) as? UITextView {
//change properties here
textField.backgroundColor = .orange
}
if let textField = self.StoriesView.viewWithTag(textFieldTag[textFieldTag.count - 1]) as? UITextView {
//change properties here
textField.backgroundColor = .green
}
}
}
It will have an output as this!!

Search bar with corner radius in swift

I want to create a view like the above image.it has a search bar with corner radius.but when i am trying to create, i am unable to make the search bar with corner radius.also i am unable to make the text field of the search bar with corner radius. i have writtenall my code in viewDidAppear method. It is ok or i have to write it in viewWillLayourSubview. so that i will be able to make the exact
same search bar like this image. also i want the seach icon to be placed slightly right.
My code is:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
for subView in searchBar.subviews {
for subsubView in subView.subviews {
if let textField = subsubView as? UITextField {
var bounds: CGRect
var placeHolder = NSMutableAttributedString()
let Name = "Search"
placeHolder = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica", size: 15.0)!])
placeHolder.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.gray, range:NSRange(location:0,length:Name.count))
textField.attributedPlaceholder = placeHolder
if let leftView = textField.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.frame.size.width = 15.0
leftView.frame.size.height = 15.0
leftView.tintColor = UIColor.gray
}
textField.layer.cornerRadius = 50.0
bounds = textField.frame
bounds.size.width = searchBar.frame.width
bounds.size.height = searchBar.frame.height
textField.bounds = bounds
textField.borderStyle = UITextField.BorderStyle.roundedRect
searchBar.backgroundImage = UIImage()
textField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
}
}
}
}*
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
for subView in searchBar.subviews {
if !subView.subviews.contains(where: { $0 as? UITextField != nil }) { continue }
guard let textField = subView.subviews.first(where: { $0 as? UITextField != nil }) as? UITextField else { return }
let placeholder = NSMutableAttributedString(
string: "Search",
attributes: [.font: UIFont(name: "Helvetica", size: 15.0)!,
.foregroundColor: UIColor.gray
])
textField.attributedPlaceholder = placeholder
textField.borderStyle = UITextField.BorderStyle.roundedRect
textField.layer.cornerRadius = textField.frame.size.height / 2
textField.layer.masksToBounds = true
textField.textColor = .white
textField.backgroundColor = .lightGray
}
searchBar.barTintColor = .white
searchBar.backgroundColor = .white
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
}
Doesn't look exactly like in the image that you linked, but actually fits better into the Apple design and works better than the code that you wrote.
For anything more sophisticated, I would advise to create a custom UISearchBar subclass.
Be aware of Apple's Human Interface Guidelines, so anything too crazy / different from default might not be accepted in the AppStore.

Create UIButtons with dynamic font size but all share same font size in UIStackView

I am using UIStackView and adding three buttons to it. I want it so that the button with the most text (B1) will be auto resized to fit the width and the other buttons will share the same font size as B1.
#IBOutlet weak var stackView: UIStackView!
var btnTitles = [String]()
btnTitles.append("Practice Exams")
btnTitles.append("Test Taking Tips")
btnTitles.append("About")
createButtons(buttonTitles: btnTitles)
var min = CGFloat(Int.max) // keep track of min font
func createButtons(buttonTitles: [String]) {
var Buttons = [UIButton]()
for title in buttonTitles {
let button = makeButtonWithText(text: title)
// set the font to dynamically size
button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.baselineAdjustment = .alignCenters // I think it keeps it centered vertically
button.contentEdgeInsets = UIEdgeInsetsMake(5, 10, 5, 10); // set margins
if (button.titleLabel?.font.pointSize)! < min {
min = (button.titleLabel?.font.pointSize)! // to get the minimum font size of any of the buttons
}
stackView.addArrangedSubview(button)
Buttons.append(button)
}
}
func makeButtonWithText(text:String) -> UIButton {
var myButton = UIButton(type: UIButtonType.system)
//Set a frame for the button. Ignored in AutoLayout/ Stack Views
myButton.frame = CGRect(x: 30, y: 30, width: 150, height: 100)
// background color - light blue
myButton.backgroundColor = UIColor(red: 0.255, green: 0.561, blue: 0.847, alpha: 1)
//State dependent properties title and title color
myButton.setTitle(text, for: UIControlState.normal)
myButton.setTitleColor(UIColor.white, for: UIControlState.normal)
// set the font to dynamically size
myButton.titleLabel!.font = myButton.titleLabel!.font.withSize(70)
myButton.contentHorizontalAlignment = .center // align center
return myButton
}
I wanted to find the minimum font size and then set all the buttons to the minimum in viewDidAppear button the font prints as 70 for all of them even though they clearly appear different sizes (see image)
override func viewDidAppear(_ animated: Bool) {
print("viewDidAppear")
let button = stackView.arrangedSubviews[0] as! UIButton
print(button.titleLabel?.font.pointSize)
let button1 = stackView.arrangedSubviews[1] as! UIButton
print(button1.titleLabel?.font.pointSize)
let button2 = stackView.arrangedSubviews[2] as! UIButton
print(button2.titleLabel?.font.pointSize)
}
image
You can try playing around with this func to return the scaled-font-size of a label:
func actualFontSize(for aLabel: UILabel) -> CGFloat {
// label must have text, must have .minimumScaleFactor and must have .adjustsFontSizeToFitWidth == true
guard let str = aLabel.text,
aLabel.minimumScaleFactor > 0.0,
aLabel.adjustsFontSizeToFitWidth
else { return aLabel.font.pointSize }
let attributes = [NSAttributedString.Key.font : aLabel.font]
let attStr = NSMutableAttributedString(string:str, attributes:attributes as [NSAttributedString.Key : Any])
let context = NSStringDrawingContext()
context.minimumScaleFactor = aLabel.minimumScaleFactor
_ = attStr.boundingRect(with: aLabel.bounds.size, options: .usesLineFragmentOrigin, context: context)
return aLabel.font.pointSize * context.actualScaleFactor
}
On viewDidAppear() you would loop through the buttons, getting the smallest actual font size, then set the font size for each button to that value.
It will take some experimentation... For one thing, I've noticed in the past that font-sizes can get rounded - so setting a label's font point size to 20.123456789 won't necessarily give you that exact point size. Also, since this changes the actual font size assigned to the labels, you'll need to do some resetting if you change the button title dynamically. Probably also need to account for button frame changes (such as with device rotation, etc).
But... here is a quick test that you can run to see the approach:
class TestViewController: UIViewController {
let stackView: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .vertical
v.alignment = .center
v.distribution = .fillEqually
v.spacing = 8
return v
}()
var btnTitles = [String]()
var theButtons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fixButtonFonts()
}
func setupUI() -> Void {
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40),
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40),
])
btnTitles.append("Practice Exams")
btnTitles.append("Test Taking Tips")
btnTitles.append("About")
createButtons(buttonTitles: btnTitles)
}
func fixButtonFonts() -> Void {
var minActual = CGFloat(70)
// get the smallest actual font size
theButtons.forEach { btn in
if let lbl = btn.titleLabel {
let act = actualFontSize(for: lbl)
// for debugging
//print("actual font size: \(act)")
minActual = Swift.min(minActual, act)
}
}
// set font size for each button
theButtons.forEach { btn in
if let lbl = btn.titleLabel {
lbl.font = lbl.font.withSize(minActual)
}
}
}
func createButtons(buttonTitles: [String]) {
for title in buttonTitles {
let button = makeButtonWithText(text: title)
// set the font to dynamically size
button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
// .minimumScaleFactor is required
button.titleLabel!.minimumScaleFactor = 0.05
button.titleLabel!.baselineAdjustment = .alignCenters // I think it keeps it centered vertically
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10); // set margins
stackView.addArrangedSubview(button)
theButtons.append(button)
}
}
func makeButtonWithText(text:String) -> UIButton {
let myButton = UIButton(type: UIButton.ButtonType.system)
//Set a frame for the button. Ignored in AutoLayout/ Stack Views
myButton.frame = CGRect(x: 30, y: 30, width: 150, height: 100)
// background color - light blue
myButton.backgroundColor = UIColor(red: 0.255, green: 0.561, blue: 0.847, alpha: 1)
//State dependent properties title and title color
myButton.setTitle(text, for: UIControl.State.normal)
myButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
// set the font to dynamically size
myButton.titleLabel!.font = myButton.titleLabel!.font.withSize(70)
myButton.contentHorizontalAlignment = .center // align center
return myButton
}
func actualFontSize(for aLabel: UILabel) -> CGFloat {
// label must have text, must have .minimumScaleFactor and must have .adjustsFontSizeToFitWidth == true
guard let str = aLabel.text,
aLabel.minimumScaleFactor > 0.0,
aLabel.adjustsFontSizeToFitWidth
else { return aLabel.font.pointSize }
let attributes = [NSAttributedString.Key.font : aLabel.font]
let attStr = NSMutableAttributedString(string:str, attributes:attributes as [NSAttributedString.Key : Any])
let context = NSStringDrawingContext()
context.minimumScaleFactor = aLabel.minimumScaleFactor
_ = attStr.boundingRect(with: aLabel.bounds.size, options: .usesLineFragmentOrigin, context: context)
return aLabel.font.pointSize * context.actualScaleFactor
}
}
Result:

Why are NSAttributedString's attributes influencing other AttributedStrings?

In this case I'm setting a UILabel's attributedText with a combined NSAttributedString with different attributes for each line, and for some reason some AttributedString attributes influence the other AttributedStrings, but I thought their attributed are bound to the range of that particular AttributedString. I'm basically expecting that the NSAttributedString automatically gets its range set up when I append it to the NSMutableAttributedString.
Am I wrong?
In this case the shadows applies to the other appended AttributedStrings, in another case it is the bold font that overrides all fonts to come in the next AttributedStrings. Strange.
Here is some sample code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textLabel.numberOfLines = 0
textLabel.lineBreakMode = .byWordWrapping
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let attributedText = NSMutableAttributedString(string: "")
let fatString = NSMutableAttributedString(string: "Bold", attributes: [NSAttributedString.Key.foregroundColor : UIColor.green,
NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16),
NSAttributedString.Key.backgroundColor : UIColor.lightGray,
NSAttributedString.Key.shadow : myShadow])
let normalString = NSAttributedString(string: "\n\nNormal", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)])
let italicString = NSAttributedString(string: "\n\nItalic", attributes: [NSAttributedString.Key.foregroundColor : UIColor.yellow,
NSAttributedString.Key.font : UIFont.italicSystemFont(ofSize: 16)])
let otherFontString = NSAttributedString(string: "\n\nBold + Italic", attributes: [NSAttributedString.Key.foregroundColor : UIColor.gray,
NSAttributedString.Key.font : UIFont(descriptor: UIFontDescriptor().withSymbolicTraits([.traitBold, .traitItalic])!, size: 16)])
let normalString2 = NSAttributedString(string: "\n\nUnderlined", attributes: [NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.foregroundColor : UIColor.red,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)])
attributedText.append(fatString)
attributedText.append(normalString)
attributedText.append(italicString)
attributedText.append(otherFontString)
attributedText.append(normalString2)
textLabel.attributedText = attributedText
}
}