TableView cell messing up constraints - iphone

I've a tableView where I present news feed from my Database. The amount of cells right now is around 20 but it will continue to grow for sure.
In a cell I've three labels: Title, Date and a short description. I've set up all of my constraints using storyboards. And the height of my tableView cell is dynamically changing according to the size of my content.
The problem is whenever I load my feed, one of the cells is always messed up. There is a constraint between Title label and date label >=30 so it's always at least one cell that will have a title label with a constant width of 190 (the others are always correctly displayed). If I scroll my tableView up and return back to that cell it will come back to normal but the height of the cell will stay the same (too big for the content).
What can be causing the problem?
Thank you in advance!
Edit:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! FinalNews
cell.backgroundColor = UIColor(red: 249/255, green: 237/255, blue: 229/255, alpha: 1)
let chevron = UIImage(named: "Next4.png")
cell.accessoryType = .DisclosureIndicator
cell.accessoryView = UIImageView(image: chevron!)
cell.textLabel?.textColor = UIColor.blackColor()
// Feeds dictionary.
var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as! NSDictionary
let firstiteration: String = (myFeed.objectAtIndex(indexPath.row).objectForKey("Description")?.stringByReplacingOccurrencesOfString("<b>", withString: ""))!
let seconditeration = firstiteration.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
let category: String = myFeed[indexPath.row].objectForKey("CategoryID") as! String
func getCategory(value: String) -> String {
var end = value.endIndex
for var i = value.startIndex;
i < value.endIndex;
i = i.successor() {
if value[i] == "\n" {
end = i
break
}
}
return value[value.startIndex..<end]
}
let counter1 = getCategory(category)
if counter1 == "1"{
cell.titleLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("DosNum") as? String
cell.descLabel.text = " \n "
cell.descLabel.textColor = UIColor(red: 249/255, green: 237/255, blue: 229/255, alpha: 1)
cell.dateLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
}
else{
cell.titleLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Title") as? String
cell.descLabel.text = seconditeration
cell.descLabel.textColor = UIColor.blackColor()
cell.dateLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
}
var shorDate: String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.stringFromDate(NSDate())
}
let today1 = shorDate
let dateIter = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_publication") as? String
let dateIter1: String = (dateIter as? NSString)!.substringToIndex(10)
let calendar = NSCalendar.currentCalendar()
//let twoDaysAgo = calendar.dateByAddingUnit(.Day, value: -1, toDate: NSDate(), options: [])
var shorDate1: String {
let dateFormatter = NSDateFormatter()
let oneDaysAgo = calendar.dateByAddingUnit(.Day, value: -1, toDate: NSDate(), options: [])
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.stringFromDate(oneDaysAgo!)
}
let oneDaysAgo1 = shorDate1
if today1 == dateIter1{
cell.dateLabel.text = "Сегодня"
//someDate is berofe than today
} else if dateIter1 == oneDaysAgo1 {
//someDate is equal or after than today
cell.dateLabel.text = "Вчера"
} else {
cell.dateLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
}
return cell
}

Related

Getting tableview cell value nil in swift

I have tableview with 3 sections. Every section has a row. In my simulator screen only 2 sections are showing . If I will scroll the table view the third cell will be shown. There is a save button, by clicking it I am passing data to another view controller. If I will not scroll the tableview and click the save button then the cell of third section is nil.
My code is:-
let indexPath = IndexPath(row: 0, section: 0)
let indexPath1 = IndexPath(row: 0, section: 1)
let indexPath2 = IndexPath(row: 0, section: 2)
let cell1 = tableView.cellForRow(at: indexPath) as? PatientInformationTableViewCell
let cell2 = tableView.cellForRow(at: indexPath1) as? PatientAdressTableViewCell
let cell3 = tableView.cellForRow(at: indexPath2) as? OtherInfoTableViewCell
guard let name = nameTextField.text,
let id = cell1.patientTextField.text,
let dob = cell1.dobTextField.text,
let street = cell1.streetAdressTextField.text,
let city = cell2.cityTextField.text,
let state = cell2.stateTextField.text,
let zip = cell2.zipTextField.text,
let country = cell2.CountryTextField.text,
let practioner = cell3.practionerTextField.text,
let lcode = cell3.lcodeTextField.text,
let qty = cell3.qtyTextField.text,
let prescription = cell3.PrescriptionTextView.text,
let klLevel = cell3.kLevelTextField.text,
let deviceType = cell3.deviceTypeTextField.text,
let guardian = cell3.guardianTextField.text,
let relationship = cell3.relationshipwithPatient.text
else {
return
}
let patient = PatientInformationModel(name: name, id: id, dob: dob, streetAdress: street, city: city, state: state, zip: zip, country: country, klevel: klLevel, deviceType: deviceType, visitType: "visitType", deliveryLocation: "deliveryLocation", lCode: lcode, qty: qty, descripePrescription: prescription, practioner: practioner, guardian: guardian, relationship: relationship)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(patient) {
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: "SavedPerson")
}
if let storyBoard = UIStoryboard(name: "Pdf", bundle: nil) as? UIStoryboard{
captureSignature { (sign) in
signatureImage = sign?.image
print("signature image is \(signatureImage)")
}
let PatientListViewController = storyBoard.instantiateViewController(identifier: "GeneratePdfViewController") as? GeneratePdfViewController
PatientListViewController?.signatureImage = signatureImage
self.navigationController?.pushViewController(PatientListViewController!, animated: true)
}
in this above code, if i am clicking on save button without scrolling to bottom , i am getting cell3 value nil.Is there any soution. please help me.

How to retrieve a value from Firestore to change the text of button in table cell for every listen item?

I have tableview in which there is list item and every cell possess a button, I want to fix the text and color of the button based on a boolean value retrieved from firestore, every cell's button have certain text and color based on that value only, I know the syntax to set the text and color for the button in swift, I am just not able to do on the basis of the value from the firestore, below is the code
code for retrieving the list, concerned value is checkl1value
func getComments() {
//print(postId + "received")
let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")
commentsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let username = data["comment_author_username"] as? String ?? ""
let comment = data["comment_author_comment"] as? String ?? ""
let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
let fullname = data["comment_author_fullname"] as? String ?? ""
let email = data["comment_author_email"] as? String ?? ""
let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
let commentuser_id = data["comment_author_id"] as? String ?? ""
self.checkl1value = data["l1"] as? DarwinBoolean
let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id )
self.comments.append(newComment)
}
self.tableView.reloadData()
}
}
}
}
Code for cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
cell.commentLikebutton.tag = indexPath.row
cell.commentLikebutton.addTarget(self, action: #selector(likeaction1(_:)), for: .touchUpInside)
if checkl1value == true {
cell.commentLikebutton.setTitle("Text1", for: .normal)
// cell.commentLikebutton.backgroundColor = UIColor(red: 17.0/255.0, green: 119.0/255.0, blue: 151.0/255.0, alpha: 1.0)
cell.commentLikebutton.backgroundColor = UIColor.red
//cell.commentLikebutton.backgroundColor = UIColor?.red()
}
else{
cell.commentLikebutton.setTitle("Text2", for: .normal)
}
cell.set(comment: comments[indexPath.row])
return cell
}
Add something like this on the top of cellForRowAt
let thisComment = self.comments[indexPath.row]
let checkl1value = thisComment.checkl1value
I think the error is that your checkl1Value always get changed with the value of the last item in the array. You can do something like this:
var booleanValues = [DarwinBoolean]()
func getComments() {
let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")
commentsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let username = data["comment_author_username"] as? String ?? ""
let comment = data["comment_author_comment"] as? String ?? ""
let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
let fullname = data["comment_author_fullname"] as? String ?? ""
let email = data["comment_author_email"] as? String ?? ""
let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
let commentuser_id = data["comment_author_id"] as? String ?? ""
// self.checkl1value = data["l1"] as? DarwinBoolean
booleanValues.append(data["l1"] as? DarwinBoolean ?? false)
let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id )
self.comments.append(newComment)
}
self.tableView.reloadData()
}
}
}
}
CellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
cell.commentLikebutton.tag = indexPath.row
cell.commentLikebutton.addTarget(self, action: #selector(likeaction1(_:)), for: .touchUpInside)
if booleanValues[indexPath.row] {
cell.commentLikebutton.setTitle("Text1", for: .normal)
// cell.commentLikebutton.backgroundColor = UIColor(red: 17.0/255.0, green: 119.0/255.0, blue: 151.0/255.0, alpha: 1.0)
cell.commentLikebutton.backgroundColor = UIColor.red
//cell.commentLikebutton.backgroundColor = UIColor?.red()
} else {
cell.commentLikebutton.setTitle("Text2", for: .normal)
}
cell.set(comment: comments[indexPath.row])
return cell
}

Displaying wrong data after scrolled TableView

I tried to update TableView cell when click cell from CollectionView with key word of class.
For example, when I click "all", it should perform all data.
When I click "a", it should perform class with "a".
It looks like all perfect until I scroll down TableView.
All data display which is not my intension, it should only show specify data even scroll up/down TableView.
Is it related to dequeueReusableCell issue?
I use FMDB to query data when click CollectionView cell.
I attach gif
and hope it could be better to understand my problem.
Can someone help me out with this please? Thanks.
add cellForRow function here.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ListTableViewCell
if navigationItem.searchController?.isActive == true{
cell.itemImage.image = searchArray[indexPath.row].thumbnailImage()
cell.nameLBL.text = "name:\(searchArray[indexPath.row].name ?? "")"
cell.quantityLBL.text = "Qty:\(searchArray[indexPath.row].quantity ?? 0)pcs"
cell.amountLBL.text = "amount:\(searchArray[indexPath.row].amount ?? 0)"
cell.dateLBL.text = "date:\(searchArray[indexPath.row].date ?? "")"
cell.storeLBL.text = "store:\(searchArray[indexPath.row].store ?? "")"
cell.classLBL.text = "class:\(searchArray[indexPath.row].itemClass ?? "")"
if let reminder = searchArray[indexPath.row].reminder {
let reminderText = ""
cell.reminderLBL.text = "\(reminder)" + reminderText
reminderStatus = true
}else{
cell.reminderLBL.text = "reminder:NO"
if self.array[indexPath.row].reminder == nil{
cell.reminderLBL.text = "reminder:NO"
}
reminderStatus = false
}
}else{
cell.itemImage.image = array[indexPath.row].thumbnailImage()
cell.nameLBL.text = "name:\(array[indexPath.row].name ?? "")"
cell.quantityLBL.text = "Qty:\(array[indexPath.row].quantity ?? 0)pcs"
cell.amountLBL.text = "amount:\(array[indexPath.row].amount ?? 0)"
cell.dateLBL.text = "date:\(array[indexPath.row].date ?? "")"
cell.storeLBL.text = "store:\(array[indexPath.row].store ?? "")"
cell.classLBL.text = "class:\(array[indexPath.row].itemClass ?? "")"
if let reminder = array[indexPath.row].reminder {
let reminderText = ""
cell.reminderLBL.text = "\(reminder)" + reminderText
reminderStatus = true
}else{
cell.reminderLBL.text = "reminder:NO"
if self.array[indexPath.row].reminder == nil{
cell.reminderLBL.text = "reminder:NO"
}
reminderStatus = false
}
print(array.count)
}
return cell
}
add didSelectItemAt function here.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
reloadTableViewAndDatabase()
case 1:
reloadTableViewAndDatabase(itemClass: searchStringOfDaily)
case 2:
reloadTableViewAndDatabase(itemClass: searchStringOfCare)
case 3:
reloadTableViewAndDatabase(itemClass: searchStringOfCosmetic)
default:
reloadTableViewAndDatabase()
}
}
And function which may be factor.
let searchStringOfDaily = "SELECT * FROM Data where itemClass = 'a';"
let searchStringOfCare = "SELECT * FROM Data where itemClass = 'b';"
let searchStringOfCosmetic = "SELECT * FROM Data where itemClass = 'c';"
func reloadTableViewAndDatabase()
{
self.dbHelper.searchAllDataFromDatabase { (dataArray) in
self.array = dataArray
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func reloadTableViewAndDatabase(itemClass:String)
{
self.dbHelper.searchDataFromDatabase(completionHandler: { (dataArray) in
self.array = dataArray
DispatchQueue.main.async {
self.tableView.reloadData()
}
}, search: itemClass)
}
public func searchDataFromDatabase(completionHandler:([Data]) -> (),search:String) {
var searchResultArray:[Data] = []
if self.database == nil{
self.database = FMDatabase(path: self.databasePath)
}
if self.database.open(){
let searchString = search
do{
let resultNext = try self.database.executeQuery(searchString, values: nil)
while resultNext.next(){
let dataName = resultNext.string(forColumn: "name")
let dataQuantity = resultNext.int(forColumn: "quantity")
let dataAmount = resultNext.int(forColumn: "amount")
let dataDate = resultNext.string(forColumn: "date")
let dataStore = resultNext.string(forColumn: "store")
let dataImageName = resultNext.string(forColumn: "imageName")
let dataItemClass = resultNext.string(forColumn: "itemClass")
let dataReminder = resultNext.string(forColumn: "reminder")
let data = Data(name: dataName!, quantity: Int(dataQuantity), amount: Int(dataAmount), date: dataDate!, store: dataStore!, imageName: dataImageName ?? "", reminder: Int(dataReminder!), itemClass: dataItemClass!)
searchResultArray.append(data)
}
print("query success")
}catch{
print(error.localizedDescription)
}
self.database.close()
}
completionHandler(searchResultArray)
}

TableView for Messaging App Not Updating Cells when retrieveMessages() is Called. Swift 4 & Firebase

The app allows users to have their own chat bubble colors and avatars. My issue is that when I send the message from another device, and I receive the message, my SENT cell bubble color and avatar changes. But the text remains correct. But when I move the cell out of the view, and bring it back, it changes to the correct color/avatar. Adding reloadData to the retrieveMessages() doesn't help, only cause the cells to flash quickly.
This is how I am receiving the messages
func retrieveMessages() {
let messageDB = Database.database().reference().child("ChatRooms").child(chatRoomID).child("Messages")
messageDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String,Any>
let message = snapshotValue["MessageBody"]! as! String
let sentby = snapshotValue["Sender"]! as! String
let sentUid = snapshotValue["userID"]! as! String
let messageObject = Message()
messageObject.messageBody = message
messageObject.sender = sentby
messageObject.userID = sentUid
messageObject.key = snapshot.key
self.messageArray.append(messageObject)
self.configureTableView()
let indexPath: IndexPath = IndexPath(row: self.messageArray.count - 1, section: 0)
self.messageTableView.insertRows(at: [indexPath], with: .left)
self.scrollToBottom()
}
}
This is my cellForRowAt. (I understand it's a little long. Still need to refactor what I can)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell
configureTableView()
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureReconizer:)))
lpgr.minimumPressDuration = 0.5
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
cell.addGestureRecognizer(lpgr)
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(gestureReconizer:)))
tap.delegate = self
tap.numberOfTapsRequired = 2
tap.delaysTouchesBegan = true
cell.messageBackground.addGestureRecognizer(tap)
let messageIndex = messageArray[indexPath.row]
cell.messageBody.text = messageIndex.messageBody
cell.avatar = self.myAvatar
cell.senderUsername.text = messageIndex.sender
cell.avatarImageView.image = UIImage(named: myAvatar)
cell.selectionStyle = .none
cell.likeButtonContraint.constant = 400
if likedMessagesArray.contains(messageIndex.key) {
cell.likeButton.layer.opacity = 100
cell.likeButtonContraint.constant = 2
cell.likeButton.isHidden = false
} else {
cell.likeButtonContraint.constant = 400
cell.layoutIfNeeded()
}
if self.blockedUsersArray.contains(messageArray[indexPath.row].userID) {
self.messageArray.remove(at: indexPath.row)
self.messageTableView.reloadData()
print("User \(messageIndex.sender) is blocked")
} else {
print("User \(messageIndex.sender) not blocked")
}
var color: String?
color = self.myColor
switch color {
case "red" : cell.messageBackground.backgroundColor = UIColor.flatRed()
case "gray": cell.messageBackground.backgroundColor = UIColor.flatGray()
case "lime": cell.messageBackground.backgroundColor = UIColor.flatLime()
case "mint": cell.messageBackground.backgroundColor = UIColor.flatMint()
case "coffee": cell.messageBackground.backgroundColor = UIColor.flatCoffee()
case "pink": cell.messageBackground.backgroundColor = UIColor.flatPink()
default: cell.messageBackground.backgroundColor = UIColor.gray
}
cell.avatarImageView.image = UIImage(named: self.myAvatar)
cell.avatarImageView.backgroundColor = UIColor.white
cell.messageBackground.layer.opacity = 82
cell.messageBackground.frame.size.width = view.frame.size.width
cell.contentView.transform = CGAffineTransform(scaleX: -1, y: 1)
cell.messageBackground.transform = CGAffineTransform(scaleX: -1, y: 1)
if cell.senderUsername.text != Auth.auth().currentUser!.email {
let messageDB = Database.database().reference().child("Users").child(messageIndex.userID)
messageDB.observe(.value) { (snapshot) in
let snapshotValue = snapshot.value as? NSDictionary
let avatar = snapshotValue!["avatar"]! as! String
cell.avatarImageView.image! = UIImage(named: avatar)!
var color: String?
let chatColor = snapshotValue!["chatColor"] as! String
color = chatColor
switch color {
case "red" : cell.messageBackground.backgroundColor = UIColor.flatRed()
case "gray": cell.messageBackground.backgroundColor = UIColor.flatGray()
case "lime": cell.messageBackground.backgroundColor = UIColor.flatLime()
case "mint": cell.messageBackground.backgroundColor = UIColor.flatMint()
case "coffee": cell.messageBackground.backgroundColor = UIColor.flatCoffee()
case "pink": cell.messageBackground.backgroundColor = UIColor.flatPink()
default: cell.messageBackground.backgroundColor = UIColor.gray
}
}
cell.avatarImageView.backgroundColor = UIColor.white
cell.messageBackground.layer.opacity = 82
cell.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
cell.messageBackground.transform = CGAffineTransform(scaleX: 1, y: 1)
}
return cell
}
Before Receiving Message. Freshly loaded
After Receiving Message, but notice the text stays correct. But my cell changes it's bubble color and avatar
Moved cell out of view
Brought cell back, cell changes to correct color, avatar
I think that you have to add reloadData method at the end of retrieveMessages()
self.messageTableView.reloadData()

Superscript string in Swift

I'm trying to make my text more readable to the user in my app. I'm reading my text from a JSON from "https://api.myjson.com/bins/ss5jb". Is there a way to superscript the verseNumber and change its color to a light gray in my collectionView enumerated string?
And is an enumerated string the best way to pair the verseNumber and verse?
import UIKit
class PageCell: UICollectionViewCell {
let textLabel: UITextView = {
let label = UITextView()
//Custom Font//
guard let customFont = UIFont(name: "CormorantGaramond-Medium", size: 20) else {
fatalError("""
Failed to load the "RCormorantGaramond-Medium" font.
Make sure the font file is included in the project and the font name is spelled correctly.
"""
)
}
//End Custom Font//
label.font = customFont
label.text = ""
label.translatesAutoresizingMaskIntoConstraints = false
label.isEditable = false
label.isUserInteractionEnabled = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(textLabel)
//textLabel Constraints
textLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 40).isActive = true
textLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
textLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true
textLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 30).isActive = true
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId2", for: indexPath) as! PageCell
let page = book?.pages[indexPath.item]
if let page = page {
let enumeratedPage = page.text.enumerated()
pageCell.textLabel.text = enumeratedPage.reduce("") { (result: String, textPair) -> String in
let result = "\(result)\n"
let verseNumber = "\(textPair.offset + 1) "
let verse = "\(textPair.element)"
return result + verseNumber + verse
}
}
return pageCell
}
There are Two Ways:
Way 1:- NSAttributed String
let mainText = "Here is a example of attributedString"
let attributeText = "attributedString"
let range = (mainText as NSString).range(of: attributeText)
let attributedString = NSMutableAttributedString(string:mainText)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
attribute.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14) , range: range)
lblTitle.attributedText = attributedString
Way :- 2 You can use HTML Property:
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Use NSAttributedStrings for this. You can change text colors, baseline offsets and fonts to achieve your desired effect.