Add Nsattributed string and string in swift - ios

I having the Dynamic data, I load that data into tableview but these data having the mixing of Attributed and normal strings.
Here I getting the as "Tap here" ,I want to dilate that string with Blue colour and pick on that it need to open the url.
I write following code but it gives error.
Binary operator '+' cannot be applied to operands of type 'String' and
'NSMutableAttributedString'
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WhatisrewardsTableViewCell", for: indexPath)as! WhatisrewardsTableViewCell
cell.imageview.image = images[indexPath.section][indexPath.row]
cell.titlelbl.text = tilenames[indexPath.section][indexPath.row]
cell.desclbl.text = descriptions[indexPath.section][indexPath.row]
let value = " here.".withTextColor(UIColor.disSatifyclr)
if (cell.desclbl.text?.contains("tap"))!{
// cell.desclbl.text?.attributedString
cell.desclbl.text = descriptions[indexPath.section][indexPath.row] + value
}
cell.desclbl.addLineSpacing()
return cell
}

You can not append the NSAttributedString to String objects. I would suggest that you generate a normal String and then add the attributed parameters to it.
func prepareURLString() -> NSMutableAttributedString {
let masterString = "To navigate to google Tap Here."
let formattedString = NSMutableAttributedString(string: masterString)
let formattedStringAttribute = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular),
NSAttributedString.Key.foregroundColor: UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1),
] as [NSAttributedString.Key : Any]
let privacyPolicyAttribute = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .bold),
NSAttributedString.Key.foregroundColor: UIColor.blue,
NSAttributedString.Key.underlineStyle: 1,
NSAttributedString.Key.link: URL(string: "https://www.google.com")!
] as [NSAttributedString.Key : Any]
formattedString.addAttributes(formattedStringAttribute, range: NSMakeRange(0, formattedString.length))
let privacyPolicyRange = (masterString as NSString).range(of: "Tap Here")
formattedString.addAttributes(privacyPolicyAttribute, range: privacyPolicyRange)
return formattedString
}
This function will return a attributed string which you can use however you want. With tableview you can pass some parameters and modify the cell's attributes strings. I have added a google link behind the 'Tap Here' and its showing the output like below :
I hope I got your question right and this helps you in some way.

Related

Clickable Link on tableview controller

Hey guys how do I make a link clickable in a table view cell as shown in the image link above ?
The information is from a Json File.
func tableView( tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "albumID", for: indexPath)
let album :[String:Any] = albums[indexPath.row]
cell.textLabel?.text = album["collectionName"] as? String
cell.detailTextLabel?.text = album["artistName"] as? String
return cell
}
You need to have UITextView as detailTextLabel
attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))
cell.detailTextLabel?.attributedText = attributedString
and then implement this method
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
UIApplication.shared.open(URL)
return false
}
You can use the below-mentioned statements to make a link of textView or label either inside tableView, collection view, or using them separately inside viewController.
If you are using textView then you can use this code mentioned below:-
let attributedString = NSMutableAttributedString(string: "Just click here to `register")
let url = URL(string: "https://www.apple.com")!
// Set the 'click here' substring to be the link
attributedString.setAttributes([.link: url], range: NSMakeRange(5, 10))
self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false
// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
or
if you are using labels then you can use this code mentioned below:-
var attributedString = NSMutableAttributedString(string: "String with a link", ``attributes: nil)
let linkRange = NSRange(location: 14, length: 4) // for the word "link" in the string above
let linkAttributes = [
NSAttributedString.Key.foregroundColor: UIColor(red: 0.05, green: 0.4, blue: 0.65, alpha: 1.0),
NSAttributedString.Key.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)
]
attributedString.setAttributes(linkAttributes, range: linkRange)
// Assign attributedText to UILabel
label.attributedText = attributedString```

Make half of the TextView's text color Different than other 50% of the text SWIFT

I've got a large text in my UITextView and I want to make the 50% of the text's color red and the other 50% green . I've added NSMutableAttributedString in the TextView but it works's for the full range of the text . How to divide the textView's text into two sections and color them into red and green ?
let strNumber: NSString = self.text as NSString // TextView Text
let range = (strNumber).range(of: strNumber as String)
let attribute = NSMutableAttributedString.init(string: strNumber as String)
attribute.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14) , NSAttributedString.Key.foregroundColor : UIColor.red], range: range)
self.attributedText = attribute
It seems you have an extension to UITextView. The following extension function will make the existing attributed text of a text view be half red and half green. All other existing attributes, if any, will remain.
extension UITextView {
func makeHalfRedGreen() {
if let text = self.text {
let half = text.count / 2
let halfIndex = text.index(text.startIndex, offsetBy: half)
let firstRange = NSRange(..<halfIndex, in: text)
let secondRange = NSRange(halfIndex..., in: text)
let attrTxt = NSMutableAttributedString(attributedString: attributedText)
attrTxt.addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)
attrTxt.addAttribute(.foregroundColor, value: UIColor.green, range: secondRange)
attributedText = attrTxt
}
}
}
Try to use function like below
text_lbl.attributedText = self.decorateText(txt1: "Red Color", txt2: “Blue Color”)
func decorateText(txt1:String, txt2:String)->NSAttributedString{
let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-SemiBold", size: 14.0)!] as [NSAttributedStringKey : Any]
let textPartOne = NSMutableAttributedString(string: txt1, attributes: textAttributesOne)
let textPartTwo = NSMutableAttributedString(string: txt2, attributes: textAttributesTwo)
let textCombination = NSMutableAttributedString()
textCombination.append(textPartOne)
textCombination.append(textPartTwo)
return textCombination
}

How to change UIButton attributed text colour programatically?

I have a subclass (KeyButton) of UIButton where I am applying certain styles for the button. The following code adds the attributed text for buttons in the ViewController.
func superScriptText(text: String, button: KeyButton, fontSize: Int) {
let font:UIFont? = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.light)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:CGFloat(fontSize))
let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font:font!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:15], range: NSRange(location:1,length:1))
button.setAttributedTitle(attString, for: .normal)
}
How can I change the color of attributed text for the button in the class?
Just change:
let attString:NSMutableAttributedString =
NSMutableAttributedString(string: text, attributes: [.font:font!])
to:
let attString:NSMutableAttributedString =
NSMutableAttributedString(string: text, attributes: [.font:font!, .foregroundColor: UIColor.red])
NSAttributedStringKey.foregroundColor is used for the text color, see more options in docs.
You have to add the .foregroundColor key with a UIColor object as the value to the NSAttributedStrings attributes dictionary.
Example (assuming you have added a custom button in storyboard):
class CustomButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
let text = "CustomButton"
let font = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textColor = UIColor.orange
let attributes: [NSAttributedStringKey: Any] = [
.font: font,
.foregroundColor: textColor
]
let attributedText = NSAttributedString(string: text, attributes: attributes)
self.setAttributedTitle(attributedText, for: .normal)
}
}
I couldn't do this through UIButton subclass. I created the subclass of NSAttributtedText and add the following method:
var textColor: UIColor?
func setSuperScript(text: String, button: KeyButton, fontSize: Int) {
let font:UIFont? = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.light)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:CGFloat(fontSize))
let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font:font!, .foregroundColor: textColor!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:15, .foregroundColor: textColor!,], range: NSRange(location:1,length:1))
button.setAttributedTitle(attString, for: .normal)
}
I am setting the color based on the logic I have and then set the attributed string color accordingly.

How to color potion of an UILabel in swift 3

I want to achieve something like this without using 2 labels.
How can I create an UILabel like this.Please help me.
You can use the NSBackgroundColorAttributeName property of the NSMutableAttributedString to achieve the above result
var attributedString = NSMutableAttributedString(string:yourString)attributedString.addAttribute(NSBackgroundColorAttributeName, value: .redColor() , range: range)
yourLabel.attributedText = attributedString
For achieving this output we use NSAttribute class
Try below code
//This is for setting border of UILabel
let labelColor = UIColor(colorLiteralRed: 255.0/255.0, green: 115.0/255.0, blue: 116.0/255.0, alpha: 1.0)
lblNoOfDays.layer.masksToBounds = true
lblNoOfDays.layer.borderWidth = 1.0
lblNoOfDays.layer.borderColor = labelColor.cgColor
//This is value we display
let strValueTitle = "No of Days"
let strValue = "04"
//Attribute dictionary we use
//NSFontAttributeName:- sets font and it's size
//NSForegroundColorAttributeName:- sets text colour
//NSBackgroundColorAttributeName:- sets background color
let attributeTitle = [NSFontAttributeName: UIFont.systemFont(ofSize: 11.0), NSForegroundColorAttributeName: labelColor, NSBackgroundColorAttributeName: UIColor.clear]
let attributeVal = [NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName: UIColor.white, NSBackgroundColorAttributeName: labelColor]
//Implement attributes to string
let attributTitleString = NSMutableAttributedString(string: strValueTitle, attributes: attributeTitle)
let attributeValue = NSAttributedString(string: strValue, attributes: attributeVal)
//Append attributed string
attributTitleString.append(attributeValue)
//Assign attributed string to label
lblNoOfDays.attributedText = attributTitleString
lblNoOfDays.sizeToFit()
You need to set padding in UILabel for getting desired output.

Attributed text with two text alignments

Does anyone know how to achieve two different text alignments in one string?
This is what I want the textView to show:
label value
My code:
let txtView = cell.viewWithTag(77) as! UITextView
let leftStyle = NSMutableParagraphStyle()
leftStyle.alignment = NSTextAlignment.Left
let rightStyle = NSMutableParagraphStyle()
rightStyle.alignment = NSTextAlignment.Right
let attText = NSMutableAttributedString(string: "label", attributes: [NSParagraphStyleAttributeName: leftStyle])
attText.appendAttributedString(NSAttributedString(string: " "))
attText.appendAttributedString(NSAttributedString(string: "value", attributes: [NSParagraphStyleAttributeName: rightStyle]))
txtView.attributedText = attText
What I get instead:
label value
Using NSMutableParagraphStyle with NSTextTab:
let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [
NSTextTab(textAlignment: .Right, location: 100, options: [:]),
]
let str = "Label\tValue\n"
+ "foo\tbar\n"
let attributed = NSAttributedString(
string: str,
attributes: [NSParagraphStyleAttributeName: paragraph]
)
let view = UITextView(frame: CGRectMake(0, 0, 120, 120))
view.textContainer.lineFragmentPadding = 10
view.attributedText = attributed
Of course, this aligns to "tabstop", but not to the edge of UITextView. When you modify the size of the view, you have to also modify the location of NSTextTab.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
let cell = Placestableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath);
//first text
let attributestitle = [NSAttributedStringKey.font:
UIFont(name: "Helvetica-Bold", size: 15.0)!,
NSAttributedStringKey.foregroundColor: UIColor.black] as [NSAttributedStringKey: Any]
//second text
let attributedString = NSMutableAttributedString(string: "\t"+String(places[indexPath.row].distance!)+" miles", attributes: [NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 8.0)!,NSAttributedStringKey.foregroundColor: UIColor.black])
let myParagraphStyle = NSMutableParagraphStyle()
myParagraphStyle.alignment = .right
myParagraphStyle.tabStops = [
NSTextTab(textAlignment: .right, location: 300, options: [:]),
]
let attributedStringtitle = NSMutableAttributedString(string: places[indexPath.row].title!, attributes: attributestitle)
//adding the right alignment to the second text alone
attributedString.addAttributes([.paragraphStyle: myParagraphStyle], range: NSRange(location: 0, length: attributedString.length))
//combining two texts with different alignments.
let combination = NSMutableAttributedString()
combination.append(attributedStringtitle)
combination.append(attributedString)
cell.textLabel?.attributedText = combination
return cell;
}

Resources