NSAttributedString combination of 2 Strings with new line - ios

I'm trying to achieve this kind of date
inside a collection view cell.
So i have the day's number and the month on 2 separate strings.
var day = example.date
var month = example.month
and with the functions below I'm changing them font color etc.
func formatMonth(fullString: String, fontSize: Double) -> NSMutableAttributedString
{
let range = (fullString as NSString).range(of: fullString)
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: fullString)
myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Bold", size: CGFloat(fontSize))!
, NSForegroundColorAttributeName : UIColor.red], range: range)
return myMutableString
}
func formatDay(fullString: String, fontSize: Double) -> NSMutableAttributedString
{
let range = (fullString as NSString).range(of: fullString)
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: fullString)
myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue", size: CGFloat(fontSize))!
, NSForegroundColorAttributeName : UIColor.black], range: range)
return myMutableString
}
And the variables are becoming like this
let theMonth = formatMonth(fullString: example.month, fontSize: 15)
let theDay = formatDay(fullString: example.date, fontSize: 13)
Then i combine them
let combination = NSMutableAttributedString()
combination.append(theDay)
combination.append(theMonth)
and finally i get the combination of the text.
date.attributedText = combination
So by this approach i can see the one next to the other 8FEb
how can i add a breaking line between them?

You can add \n with day.
let theDay = formatDay(fullString: "\(example.date)\n", fontSize: 13)
You need to set NSMutableParagraphStyle to make your text center. Try like this SO answer for that, you need to make little bit changes to make it working with Swift 3 and make sure you have sufficient height to show 2 lines.

Related

NSAttributedText alignment right and left doesn't work for the same object

I have a simple extension for NSAttributedString:
convenience init(
string: String,
strikeThrough: Bool = false,
color: UIColor? = nil,
font: UIFont? = nil,
alignment: NSTextAlignment? = nil
) {
var attributes = [NSAttributedString.Key: Any]()
if strikeThrough {
attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue
}
if let color = color {
attributes[.foregroundColor] = color
}
if let font = font {
attributes[.font] = font
}
if let alignment = alignment {
let style = NSMutableParagraphStyle()
style.alignment = alignment
attributes[.paragraphStyle] = style
}
self.init(string: string, attributes: attributes)
}
And this is how I use it in code:
let baseString = "Collectives™ helps you find trusted answers faster, engage with product experts, and share knowledge around the technologies you use most."
let baseColor: UIColor.mineShaft
let baseFont = UIFont.poppinsRegular.withSize(16)
let attributedString = NSMutableAttributedString(string: baseString, color: baseColor, font: baseFont)
attributedString.append(NSAttributedString(string: "\n"))
let color = baseColor.withAlphaComponent(0.5)
let font = baseFont.withSize(12)
let originalString = NSAttributedString(string: baseString, color: color, font: font, alignment: .right)
attributedString.append(originalString)
And the results is the following:
Everything is left aligned. Why? The second part should be right aligned.
I set two style for attributes and the result is ok, try to set like this:
let style = NSMutableParagraphStyle()
style.alignment = .left
let style2 = NSMutableParagraphStyle()
style2.alignment = .right
let attributedString = NSMutableAttributedString(string: "Collectives™ helps you find trusted answers faster, engage with product experts, and share knowledge around the technologies you use most.", attributes: [.paragraphStyle: style, .foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 14, weight: .bold)])
attributedString.append(NSAttributedString(string: "\nCollectives™ helps you find trusted answers faster, engage with product experts, and share knowledge around the technologies you use most.", attributes: [.paragraphStyle: style2, .foregroundColor: UIColor.gray, .font: UIFont.systemFont(ofSize: 12, weight: .semibold)]))
yourTextContainer.attributedText = attributedString
The result:

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
}

Adding font size and custom font name to attributed string in UITextView

I have the following code to add the attributed string to the UITextView text. I need to add the custom font and font size to it in swift. How to do it?
func setAttributedString(string: String) -> NSAttributedString {
let attrString = NSMutableAttributedString(string: string)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7
paragraphStyle.minimumLineHeight = 7
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSRange(location: 0, length:attrString.length))
attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 30), range: NSRange(location: 0, length:attrString.length))
return attrString
}
I need to add the custom font and font size to the following function. How to achieve this?
In Swift 3
let attributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
NSAttributedStringKey.foregroundColor: UIColor.white]
let attributedString = NSMutableAttributedString(string: "Your string" , attributes: attributes)
Use the initializer init(string:attributes:)
https://developer.apple.com/documentation/foundation/nsattributedstring/1408136-init
let attrString = NSMutableAttributedString(string: string, attributes:
[NSFontAttributeName:UIFont(
name: "Georgia",
size: 18.0)!])
//Add more attributes here

Convert UItextview to NSAttributedString

I've a UITextView with different properties like different color in the same text, font and size. I need to pass that text into a NSAttributedString variable.
With that code I'm not able to keep the properties of the text.
How can I do?
let attr = NSAttributedString(string: textView.text)
Use the attributedString initializer of NSAttributedString and pass it your textview attributed text:
let attr = NSAttributedString(attributedString: textView.attributedText)
var myString:NSString = textView.text
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:myString.length))
textView.attributedText = myMutableString
TextView With RedFont Color :

ios swift: Is it possible to change the font style of a certain word in a string?

I am extracting from a DB contents as strings. With a method I extract the longest word out of this string.
Now I would like to print out the entire string to a text label but would like to highlight the longest word in a different color and text style within the string.
How can I do that?
Do I need to cut the string into pieces - set the formatting - and put them all together again before giving it to the label?
Or is there any other (better) way?
If you already know the longest word you have to get the range of that word in the string. I prefer the NSString method rangeOfString: for this.
You then create a NSMutableAttributedString from the string, with your default attributes. Finally you apply highlighting attributes to the range you figured out earlier.
let longString = "Lorem ipsum dolor. VeryLongWord ipsum foobar"
let longestWord = "VeryLongWord"
let longestWordRange = (longString as NSString).rangeOfString(longestWord)
let attributedString = NSMutableAttributedString(string: longString, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(20)])
attributedString.setAttributes([NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor.redColor()], range: longestWordRange)
label.attributedText = attributedString
Update for Swift 5.0
let longestWordRange = (longString as NSString).range(of: longestWord)
let attributedString = NSMutableAttributedString(string: longString, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 20)])
attributedString.setAttributes([NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor : UIColor.red], range: longestWordRange)
Which looks like this in my playground:
You want to look at Attributed Strings and NSRange. You can use both of these together to create different styles for ranges in the string. Here is a snippet:
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
//Add more attributes here:
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Chalkduster", size: 24.0), range: NSRange(location: 7,length: 5))
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "AmericanTypewriter-Bold", size: 18.0)!, range: NSRange(location:2,length:4))
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Georgia", size: 36.0)!, range: NSRange(location: 0, length: 1))
myMutableString.addAttribute(NSStrokeColorAttributeName, value: UIColor.blueColor(), range: NSRange(location: 0, length: 1))
myMutableString.addAttribute(NSStrokeWidthAttributeName, value: 2, range: NSRange(location: 0, length: 1))
myMutableString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: 0, length: myString.length))
myLabel.backgroundColor = UIColor.grayColor()
//Apply to the label
myLabel.attributedText = myMutableString
NSMutableAttributedString.
You create an NSMutableAttributedString and apply the effects you'd like with addAttributes:range.
Then assign it to the attributedText property of your UILabel.

Resources