Created
January 5, 2016 12:22
-
-
Save elm4ward/9aba2d5c96cc97b12924 to your computer and use it in GitHub Desktop.
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 Foundation | |
#if os(iOS) | |
import UIKit | |
#endif | |
#if os(watchOS) | |
import WatchKit | |
#endif | |
extension NSMutableAttributedString { | |
public var fontAttribute: StringAttributer<UIFont> { | |
get { | |
return StringAttributer(string:self, attribute: NSFontAttributeName) | |
} | |
set { | |
// please the compiler | |
} | |
} | |
} | |
public struct StringAttributer<T> { | |
let string: NSMutableAttributedString | |
let attribute: String | |
public subscript(from start: Int, to end: Int) -> T? { | |
get { | |
return string.attributesAtIndex(start, effectiveRange: nil)[attribute] as? T | |
} | |
set { | |
guard let value = newValue as? AnyObject else { return } | |
string.addAttribute(attribute, value: value, range: NSMakeRange(start, end - start)) | |
} | |
} | |
} | |
let plainString = "test" | |
let attrString = NSMutableAttributedString(string:plainString) | |
attrString.fontAttribute[from: 0, to:1] = UIFont.systemFontOfSize(25, weight: UIFontWeightSemibold) | |
attrString.fontAttribute[from: 2, to:3] = UIFont.systemFontOfSize(20, weight: UIFontWeightRegular) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment