Reputation: 625
I am looking for a way to stop an NSTextView from falling back on a cascading font when certain characters in the display string are unavailable in the specified font.
I am writing an app in which it is important that the user know if certain characters (those in East Asian character sets, for example) are available in a given font. If these characters are not available, I want the field to display these as boxes, blank spaces, or something similar. However, the default is for the textview to fall back on a cascading font in which the characters are supported. Is there any way to change this behavior?
If this is not possible, might there be some way to detect which languages are supported by a given font?
Any help would be greatly appreciated.
Upvotes: 1
Views: 182
Reputation: 625
I was able to make it work by creating extensions partially based on this answer.
The solution I ended up using was to iterate through each character in the string in question and check to see if it is contained in the font's character set. If it is not, the appearance is changed (in this case, changing the color and adding strikethrough) before it is added to an attributed string containing all of characters of the original string.
This is what it ended up looking like:
extension UnicodeScalar {
func isIn(font:NSFont)-> Bool {
let coreFont:CTFont = font
let charSet:CharacterSet = CTFontCopyCharacterSet(coreFont) as CharacterSet
if charSet.contains(self) {
return true
}
return false
}
}
extension NSFont {
func supportString(_ str:String)-> NSAttributedString {
let attString = NSMutableAttributedString(string: "")
for scalar in str.unicodeScalars {
if !scalar.isIn(font: self) {
let r:CGFloat = 200
let g:CGFloat = 0
let b:CGFloat = 0
let a:CGFloat = 0.2
let color = NSColor(red: r, green: g, blue: b, alpha: a)
let attcha = NSMutableAttributedString(string: String(scalar), attributes: [NSAttributedStringKey.foregroundColor:color, NSAttributedStringKey.strikethroughStyle:NSUnderlineStyle.styleSingle.rawValue])
attString.append(attcha)
} else {
let attcha = NSAttributedString(string: String(scalar), attributes: [NSAttributedStringKey.foregroundColor:NSColor.black])
attString.append(attcha)
}
}
return attString
}
}
Upvotes: 1