how to set attributes in NSAttributedString in iOS?
I’m trying to set the infamous NSFontAttributeName property of an NSAttributedString in iOS but it just doesn’t seem to work:
- first off, none of the NS constants seem defined for iOS
- I read somewhere that I could instead work around it by passing
the CoreText consts instead. Fine… but still, The attribute
expects an NSFont and I’m stuck with UIFont or CTFontRef, neither of
which seems to work:
this doesn’t work:
CTFontRef ctFont = CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:16].fontName, [UIFont boldSystemFontOfSize:16].pointSize, NULL); [myAttString addAttribute:(NSString*)kCTFontNameAttribute value:(id)ctFont range:NSMakeRange(0, myAttString.length-1)];
this doesn’t work:
[myAttString addAttribute:(NSString*)kCTFontNameAttribute value:[UIFont boldSystemFontOfSize:16] range:NSMakeRange(0, myAttString.length-1)];
Is there anyway to make this work?
- Calling a Method at NSDate
- Why does the initial call to NSAttributedString with an HTML string take over 100 times longer than subsequent calls?
- How to flip a UIView around the x-axis while simultaneously switching subviews
- Invalid parameter exception thrown by _UIQueuingScrollView
- iOS / XCode: how to know that app has been launched with a click on notification or on springboard app icon?
- Objective-C Blocks and variable scope
3 Solutions Collect From Internet About “how to set attributes in NSAttributedString in iOS?”
I found it!
basically, turns out the string constant for the dictionary key I should been using is kCTFontAttributeName
This whole thing is a show…
The NS constants and full attributedString support will be there. Not yet in iOS5 though.
The CoreText constants do work and CTFontRef is the way I use it as well. The first block of your code should work. Can you verify your other bits of code that the problem ain’t elsewhere.
do this way:
let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let attributes = [NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : UIFont.systemFont(ofSize: 24.0), NSForegroundColorAttributeName : UIColor.blue, ] let attrString = NSAttributedString(string: "Stop\nall Dance", attributes: attributes)
- Custom font for iPad – iOS 3.2 isn't working
- Saving buffer data of AVPlayer
- NSMutableData disappearing
- Animate `backgroundColor` of a `UIView` that implements `drawRect`
- Google Weather API gone?
- swift: how to get the indexpath.row when a button in a cell is tapped?
- Objective-C: how to group a series of string constants?
- Programmatically creating constraints bound to view controller margins
- Upload image with parameters in Swift
- How to AirPrint multiple print formatters in one go?
- Simulate water/ make sprite “float” on water in spritekit
- Extract RGB Values From UIColor
- Sort NSDictionary in ascending order
- How to check if a uiimage is blank? (empty, transparent)
- 'Use of Unresolved Identifier' in Swift