UILabel.attributedText set attributes once and then just change text (string) - ios

How to set UILabel text attributes only once and then just change text (string)
mTextValue.attributedText = NSAttributedString(string: "STRING",
attributes:
[NSAttributedStringKey.strokeWidth: -3.0,
NSAttributedStringKey.strokeColor: UIColor.black])
mTextValue.text = "NEW STRING" // won't change anything
or to set new string do I have to set NSAttributedString to .attributedText again and again?

You could declare a mutableAttributed string separat and change the string of it like here:
let yourString = "my string"
let yourAttributes = [NSAttributedStringKey.strokeWidth: -3.0, NSAttributedStringKey.strokeColor: UIColor.black] as [NSAttributedStringKey : Any]
let mutableAttributedString = NSMutableAttributedString(string: yourString, attributes: yourAttributes)
let yourNewString = "my new string"
mutableAttributedString.mutableString.setString(yourNewString)
Full example:
import UIKit
class ViewController: UIViewController {
var mutableAttributedString = NSMutableAttributedString()
#IBAction func buttonTapped(_ sender: Any) {
mutableAttributedString.mutableString.setString("new string")
mainLabel.attributedText = mutableAttributedString
}
#IBOutlet weak var mainLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let yourString = "my string"
let yourAttributes = [NSAttributedStringKey.strokeWidth: -3.0, NSAttributedStringKey.strokeColor: UIColor.blue] as [NSAttributedStringKey : Any]
mutableAttributedString = NSMutableAttributedString(string: yourString, attributes: yourAttributes)
mainLabel.attributedText = mutableAttributedString
}
}

Related

IBaction to insert NSAttributedString (font/color) into UITextField

I'm a swift novice and I hope someone can help.
I want to insert text with a new color and font through a button into the text field (that uses another color and font). Not deleting the original text in the field or change its font or color.
I have managed to insert text thought the button, but no using the NSAttributedString. Don't know if the code in the IBAction will even work, usure where to place the:
let attributedTest = NSAttributedString
let test = "Testing here"
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont(name:"AvenirNext-Italic", size: 40)!,
.foregroundColor: UIColor.red,
]
let attributedTest = NSAttributedString(string: test, attributes: attributes as [NSAttributedString.Key : Any])
#IBAction func justTesting(_ sender: UIButton) {
noteTextView.text = noteTextView.text! + String(attributedTest)
}
You can use this extension to append attributed string
extension NSMutableAttributedString{
func getAttributedStringByAppending(attributedString:NSMutableAttributedString) -> NSMutableAttributedString{
let newAttributedString = NSMutableAttributedString()
newAttributedString.append(self)
newAttributedString.append(attributedString)
return newAttributedString
}
}
#IBAction func justTesting(_ sender: UIButton) {
let noteTextView = UITextView()
noteTextView.text = NSMutableAttributedString(string: noteTextView.text).getAttributedStringByAppending(attributedString: attributedTest)
}

Add text with different style to a existing label

I have a label with text and want to add more test in running time, but I want to add different style to this text that was add. Is there a way to do this?
This is the code
label.text = (label.text ?? "") + " \n \(userName)"
How do I add style to userName without changing the style of the label?
use attributed text in UILabel:
here some code.
a) some useful typedefs:
typealias AttrDict = [NSAttributedString.Key : Any]
a) create some styles:
func textAttribute() -> AttrDict{
let textFont = UIFont.systemFont(ofSize: 32)
let stdAttrib = [NSAttributedString.Key.font: textFont,
//NSParagraphStyleAttributeName: paragraphStyle2,
NSAttributedString.Key.foregroundColor: UIColor.red] as AttrDict
return stdAttrib
}
func smallTextAttribute() -> AttrDict{
let textFont = UIFont.systemFont(ofSize: 10)
let stdAttrib = [NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: UIColor.green] as AttrDict
return stdAttrib
}
c) build Your attributed String:
func myAttributedString() -> NSAttributedString {
let pieces = ["hello", "word"]
let resultAttributed = NSMutableAttributedString()
var s = ""
s = pieces[0] + "\n"
resultAttributed.append(NSAttributedString(string: s,
attributes: stdTextAttribute() ))
s = pieces[1] + "\n"
resultAttributed.append(NSAttributedString(string: s,
attributes: smallTextAttribute() ))
return resultAttributed
}
d) put in Your label/textView:
....
class ViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myLabel.numberOfLines = 0
myLabel.attributedText = myAttributedString()
}
}
I made a GIST:
https://gist.github.com/ingconti/aefc78c6d0b22f5329f906094c312a21
PLS connect UIlabel..
:)
To do this, you need to use NSMutableAttributedString, NSAttributedString and use label.attributedText, How?
Doing this:
let userName = "StackOverflow"
let prefixText = NSAttributedString(string: "this is normal ")
let font = UIFont.systemFont(ofSize: 40)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: UIColor.blue
]
let userNameWithStyle = NSAttributedString(string: userName, attributes: attributes)
let finalString = NSMutableAttributedString(attributedString: prefixText)
finalString.append(userNameWithStyle)
self.label.attributedText = finalString
Image result

make part of the text bold in a UITextField

Based on the answers here I made this code:
extension NSMutableAttributedString {
func bold(text:String, size:CGFloat) -> NSMutableAttributedString {
let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont.boldSystemFontOfSize(size)]
let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
self.appendAttributedString(boldString)
return self
}
func normal(text:String)->NSMutableAttributedString {
let normal = NSAttributedString(string: text)
self.appendAttributedString(normal)
return self
}
}
and I use it like this:
#IBOutlet weak var m_field: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let string = NSMutableAttributedString()
string.bold("Bold_text: ",size: 12).normal("normal text")
m_field.attributedText = string
}
but it doesn't work, all my text is the same (bold I think)
what am I doing wrong?
Enjoy - below code works for swift 3
let normalText = "Hi am normal"
let boldText = "And I am BOLD!"
let attributedString = NSMutableAttributedString(string:normalText)
let attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15)]
let boldString = NSMutableAttributedString(string:boldText, attributes:attrs)
attributedString.append(boldString)
txt.attributedText = attributedString
where txt is TextField outlet
assign "**string**" variable value to **attributedText** property
var m_field = UITextField()
m_field.frame = CGRect(x: 0, y: 66, width: 400, height: 100)
let string = NSMutableAttributedString()
string.bold("Bold_text: ",size: 15).normal("normal text")
m_field.attributedText = string
self.view .addSubview(m_field)

Swift Attributed Title Syntax

I'm trying to do something like this:
let introText = "This is sample "
let facebookText = "Text"
loginButton.setTitle("\(introText)\(facebookText)", forState: .Normal)
loginButton.addAttribute(NSFontAttributeName, value: UIFont(name: "Arial", size: 15.5)!, range: NSMakeRange(0, introText.characters.count))
loginButton.addAttribute(NSFontAttributeName, value: UIFont(name: "Arial-Bold", size: 15.5)!, range: NSMakeRange(introText.characters.count, facebookText.characters.count))
loginButton.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, introText.characters.count + facebookText.characters.count))
in this form:
loginButton.setAttributedTitle(NSMutableAttributedString(
string: "\(introText)\(facebookText)",
attributes: [
// attributes go here
NSForegroundColorAttributeName: UIColor.colorFromCode(0x151515),
]), forState: UIControlState.Normal)
Is it possible for me to do this? I'm having trouble figuring out how to include the range on included attributes.
EDIT
Sorry if it wasn't obvious, but what my code does is it creates an attributed string that reads "This is sample Text" with the word Text bolded as shown. I'm trying to rewrite this code to be in the form of the second syntax I'm showing, if it's even possible.
Thanks!
If you are looking for an attributed text with bolded part, this will do it for you.
extension String {
func getPartOfStringBold(boldPart:String)-> NSAttributedString{
return getPartOfStringBold(boldPart, font: UIFont(name: "Taz-Bold", size: 13)!)
}
//Make your string bold
func getPartOfStringBold(boldPart:String, font:UIFont)-> NSAttributedString{
let attributtedString = NSMutableAttributedString(string: self)
let attrs = [NSFontAttributeName:font]
let rangePart: NSRange = (attributtedString.string as NSString).rangeOfString(boldPart)
attributtedString.addAttributes(attrs, range: rangePart)
return attributtedString
}
//Make your string Italic
func getPartOfStringItalic(italicPart:String)-> NSAttributedString{
let attributtedString = NSMutableAttributedString(string: self)
if let font = UIFont(name: "Taz-LightItalic", size: 13)
{
let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.blackColor()]
let rangePart: NSRange = (attributtedString.string as NSString).rangeOfString(italicPart)
attributtedString.addAttributes(attrs, range: rangePart)
}
return attributtedString
}
}
as far as I have understood your problem, you want to make a portion of test as bold if yes then here is an extension which I am using for this purpose
import UIKit
import Foundation
extension String
{
static func makeTextBold(preBoldText:String, boldText:String, postBoldText:String, fontSzie:CGFloat) -> NSAttributedString {
let boldAttrs = [NSFontAttributeName : UIFont(name: "HelveticaNeue-Bold", size: fontSzie) as? AnyObject]
let attributedString = NSMutableAttributedString(string:boldText, attributes:boldAttrs as? [String:AnyObject])
let lightAttr = [NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: fontSzie) as? AnyObject]
let finalAttributedText = NSMutableAttributedString(string:preBoldText, attributes:lightAttr as? [String:AnyObject])
let postText = NSMutableAttributedString(string:postBoldText, attributes:lightAttr as? [String:AnyObject])
finalAttributedText.appendAttributedString(attributedString)
finalAttributedText.appendAttributedString(postText)
// print(finalAttributedText)
return finalAttributedText
}
}
So basically what this function is doing is that you pass three parameters for text and one for fot size and it will return an attributed string.
Here is an example usage for your case
myLabel.attributedText = String.makeTextBold("This is sample", boldText: "Text", postBoldText: "", fontSzie: 21)
the output would be
This is sample Text
I hope this answer the question :-)

How to customize UILabel with different Font Size and Color with multiple Variables together

I'm trying to put 3 variables in the same UILabel to make emphasis on the second word.
With one variable it work's fine. (Option 1)
//Option 1 That work with one variable
labelBoldAnswer.attributedText = secondWordBoldRed
THE RESULT 1 IS: Bold and Red
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var textFieldOriginal : UITextField!
#IBOutlet weak var labelBoldAnswer : UILabel!
#IBAction func ButtonBold(sender: AnyObject) {
var firstWord = "First Word"
var thirdWord = "Third Word"
var attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()]
var secondWordBoldRed = NSMutableAttributedString (string:textFieldOriginal.text, attributes: attrs)
//Option 1 That work with one variable
labelBoldAnswer.attributedText = secondWordBoldRed
//Option 2 That work partialy
//labelBoldAnswer.text = ("\(firstWord), \(secondWordBoldRed), \(thirdWord)")
}
SECOND TRY
With three variables, it show's all the text with code instead of showing bigger text and red in the center of the First and Third word. (Option 2)
//Option 2 That work partialy
labelBoldAnswer.text = ("\(firstWord), \(secondWordBoldRed), \(thirdWord)")
THE RESULT 2 IS NOT PERFECT:
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var textFieldOriginal : UITextField!
#IBOutlet weak var labelBoldAnswer : UILabel!
#IBAction func ButtonBold(sender: AnyObject) {
var firstWord = "First Word"
var thirdWord = "Third Word"
var attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()]
var secondWordBoldRed = NSMutableAttributedString (string:textFieldOriginal.text, attributes: attrs)
//Option 1 That work with one variable
//labelBoldAnswer.attributedText = secondWordBoldRed
//Option 2 That work partialy
labelBoldAnswer.text = ("\(firstWord), \(secondWordBoldRed), \(thirdWord)")
}
Thank's for your help!
You can either build the attributed string up, adding attributes to the different parts as you go:
let firstWord = "First Word"
let secondWord = "Insert Text"
let attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()]
let thirdWord = "Third Word"
let attributedText = NSMutableAttributedString(string:firstWord)
attributedText.appendAttributedString(NSAttributedString(string: secondWord, attributes: attrs))
attributedText.appendAttributedString(NSAttributedString(string: thirdWord))
textField.attributedText = attributedText
Or create the thing, then add an attribute to the range. This is somewhat complicated by the fact that NSAttributedString use NSRange, and Swift String use Range<String.index>.
let firstWord = "First Word"
let secondWord = "Insert Text"
let thirdWord = "Third Word"
let comboWord = firstWord + secondWord + thirdWord
let attributedText = NSMutableAttributedString(string:comboWord)
let attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()]
let range = NSString(string: comboWord).rangeOfString(secondWord)
attributedText.addAttributes(attrs, range: range)
textField.attributedText = attributedText
You need to do the following:
let attrsA = [NSFontAttributeName: UIFont.boldSystemFontOfSize(10)]
var a = NSMutableAttributedString(string:"hello", attributes:attrsA)
let attrsB = [NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()]
let b = NSAttributedString(string:"world", attributes:attrsB)
a.appendAttributedString(b)
which will create a string a that has multiple attributes mixed.
What you need to do is to construct an attributed string with all the variable values, and proper styling in the proper ranges. There are multiple solutions to this, but I would recommend you to have a look at NSMutableAttributedString:
create your "parts" exactly as you did for secondWordBoldRed
combine them using -[NSMutableAttributedString appendAttributedString:]
set labelBoldAnswer.attributedText to the NSMutableAttributedString

Resources