Created
June 14, 2015 18:48
-
-
Save sketchytech/cf4149f2dfb8c65add3b to your computer and use it in GitHub Desktop.
Functional Formatting in Swift: NSAttributedString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController { | |
typealias CharacterStyle = String -> NSAttributedString | |
typealias ParagraphStyle = [NSAttributedString] -> NSAttributedString | |
func paragraph(indent indent:CGFloat, spacing:CGFloat) -> ParagraphStyle { | |
return { attrStrings in | |
let para = NSMutableAttributedString() | |
for s in attrStrings { | |
para.appendAttributedString(s) | |
} | |
let paraStyle = NSMutableParagraphStyle() | |
paraStyle.firstLineHeadIndent = indent | |
paraStyle.paragraphSpacingBefore = spacing | |
para.addAttribute(NSParagraphStyleAttributeName, value: paraStyle, range: NSRange(location: 0,length: para.string.characters.count)) | |
return para | |
} | |
} | |
func bodyText(size:CGFloat, style:UIFontDescriptorSymbolicTraits?) -> CharacterStyle { | |
var desc = UIFontDescriptor(fontAttributes: [UIFontDescriptorTextStyleAttribute:UIFontTextStyleBody]) | |
if let style = style { | |
desc = desc.fontDescriptorWithSymbolicTraits(style) | |
} | |
let font = UIFont(descriptor: desc, size: size) | |
return { | |
string in | |
return NSMutableAttributedString(string: string, attributes:[NSFontAttributeName:font]) | |
} | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib.\ | |
// set font size and style traits | |
let bodyStyle = bodyText(12, style: nil) | |
let bodyStyleItalic = bodyText(12, style: .TraitItalic) | |
// build an array of styled attributed strings | |
let attrStrings = [bodyStyle("Hello Swift! This is a tutorial looking at "), | |
bodyStyleItalic("attributed"), bodyStyle(" strings!")] | |
// create a paragraph from the strings | |
let para = paragraph(indent:10.0, spacing: 12.0)(attrStrings) | |
// Create UITextView | |
let view = UITextView(frame: CGRect(x: 0, y: 20, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20)) | |
// Add string to UITextView | |
view.attributedText = para | |
// Add UITextView to main view | |
self.view.addSubview(view) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment