Multiple colours in an NSString
or NSMutableStrings
are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit
You can load an HTML
attributed string in Swift
as follow
var Str = NSAttributedString(
data: htmlstring.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
label.attributedText = Str
To load a html
from file
if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) {
let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)
textView.attributedText = attributedString
textView.editable = false
}
http://sketchytech.blogspot.in/2013/11/creating-nsattributedstring-from-html.html
And setup string as per your required attribute....follow this..
http://makeapppie.com/2014/10/20/swift-swift-using-attributed-strings-in-swift/
I wrote helper to add attributes easily:
- (void)addColor:(UIColor *)color substring:(NSString *)substring;
- (void)addBackgroundColor:(UIColor *)color substring:(NSString *)substring;
- (void)addUnderlineForSubstring:(NSString *)substring;
- (void)addStrikeThrough:(int)thickness substring:(NSString *)substring;
- (void)addShadowColor:(UIColor *)color width:(int)width height:(int)height radius:(int)radius substring:(NSString *)substring;
- (void)addFontWithName:(NSString *)fontName size:(int)fontSize substring:(NSString *)substring;
- (void)addAlignment:(NSTextAlignment)alignment substring:(NSString *)substring;
- (void)addColorToRussianText:(UIColor *)color;
- (void)addStrokeColor:(UIColor *)color thickness:(int)thickness substring:(NSString *)substring;
- (void)addVerticalGlyph:(BOOL)glyph substring:(NSString *)substring;
https://github.com/shmidt/MASAttributes
You can install through CocoaPods also : pod 'MASAttributes', '~> 1.0.0'
An easier solution with attributed string extension.
extension NSMutableAttributedString {
// this function attaches color to string
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
Try this and see (Tested in Swift 3 & 4)
let label = UILabel()
label.frame = CGRect(x: 120, y: 100, width: 200, height: 30)
let first = "first"
let second = "second"
let third = "third"
let stringValue = "\(first)\(second)\(third)" // or direct assign single string value like "firstsecondthird"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: first, withColor: UIColor.red) // use variable for string "first"
attributedString.setColorForText(textToFind: "second", withColor: UIColor.green) // or direct string like this "second"
attributedString.setColorForText(textToFind: third, withColor: UIColor.blue)
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
Here is expected result:
Super easy way to do this.
let text = "This is a colorful attributed string"
let attributedText =
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))
For more detail click here; https://github.com/iOSTechHub/AttributedString
To solve such kind of problems I created library in swift which is called Atributika.
let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
Style("r").foregroundColor(.red),
Style("g").foregroundColor(.green),
Style("b").foregroundColor(.blue)).attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
I made a library that makes this a lot easier. Check out ZenCopy.
You can create Style objects, and/or set them to keys to reference later. Like this:
ZenCopy.manager.config.setStyles {
return [
"token": Style(
color: .blueColor(), // optional
// fontName: "Helvetica", // optional
fontSize: 14 // optional
)
]
}
Then, you can easily construct strings AND style them AND have params :)
label.attributedText = attributedString(
["$0 ".style("token") "is dancing with ", "$1".style("token")],
args: ["JP", "Brock"]
)
You can also style things easily with regex searches!
let atUserRegex = "(@[A-Za-z0-9_]*)"
mutableAttributedString.regexFind(atUserRegex, addStyle: "token")
This will style all words with '@' in front of it with the 'token' style. (e.g. @jpmcglone)
I need to still get it working w/ everything NSAttributedString
has to offer, but I think fontName
, fontSize
and color cover the bulk of it. Expect lots of updates soon :)
I can help you get started with this if you need. Also looking for feedback, so if it makes your life easier, I'd say mission accomplished.