如何获取 UIFont 实例的字体大小?
或者,有没有人可以为 UIFont 实现这个方法?
- (UIFont *)boldFont;
这是一个旧答案,不再是最佳解决方案,请查看已接受的答案。
-(UIFont *)boldFont{
//First get the name of the font (unnecessary, but used for clarity)
NSString *fontName = self.fontName;
//Some fonts having -Regular on their names. so we have to remove that before append -Bold / -BoldMT
fontName = [[fontName componentsSeparatedByString:@"-"] firstObject];
//Then append "-Bold" to it.
NSString *boldFontName = [fontName stringByAppendingString:@"-Bold"];
//Then see if it returns a valid font
UIFont *boldFont = [UIFont fontWithName:boldFontName size:self.pointSize];
//If it's valid, return it
if(boldFont) return boldFont;
//Seems like in some cases, you have to append "-BoldMT"
boldFontName = [fontName stringByAppendingString:@"-BoldMT"];
boldFont = [UIFont fontWithName:boldFontName size:self.pointSize];
//Here you can check if it was successful, if it wasn't, then you can throw an exception or something.
return boldFont;
}
ArialMT
这样的字体中添加-BoldMT
是行不通的;它的粗体等价物是Arial-BoldMT
,而不是ArialMT-BoldMT
。 - titaniumdecoy要从UIFont实例中获取字体大小,请使用以下方法:
@property(nonatomic, readonly) CGFloat pointSize
有更多的属性可以用来描述字体大小(例如大写字母、小号等)
capHeight,xHeight,pointSize
使用以下内容来访问粗体字
UIFont* myboldFont = [UIFont boldSystemFontOfSize:11];
UIFontDescriptor
是一个相当强大的类,可以用来获取你想要的字体的 粗体 版本。它应该是完全安全和具有未来性的,因为它只需要使用公共 API,不依赖于任何字符串修改。
以下是Swift 3的代码:
extension UIFont {
func bold() -> UIFont? {
let fontDescriptorSymbolicTraits: UIFontDescriptorSymbolicTraits = [fontDescriptor.symbolicTraits, .traitBold]
let bondFontDescriptor = fontDescriptor.withSymbolicTraits(fontDescriptorSymbolicTraits)
return bondFontDescriptor.flatMap { UIFont(descriptor: $0, size: pointSize) }
}
}
这是Objective-C的代码:
@implementation UIFont (RABoldFont)
- (UIFont *)ra_boldFont
{
UIFontDescriptor *fontDescriptor = [self fontDescriptor];
UIFontDescriptorSymbolicTraits traits = fontDescriptor.symbolicTraits;
traits = traits | UIFontDescriptorTraitBold;
UIFontDescriptor *boldFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:traits];
return [UIFont fontWithDescriptor:boldFontDescriptor size:self.pointSize];
}
@end
[fontDescriptor.symbolicTraits, .traitBold]
是否等同于 fontDescriptor.symbolicTraits.union(.traitBold)
? - David JamesUIFont *anyFont;
//initialization and other stuff here
现在你想要找到它的尺寸大小
CGFloat fontSize= [anyFont pointSize];
kCTFontBoldTrait
。Swift 3版本的Rafał Augustyniak答案
extension UIFont {
func boldFont() -> UIFont? {
let fontDescriptor = self.fontDescriptor
let fontDescriptorSymbolicTraits: UIFontDescriptorSymbolicTraits = [ fontDescriptor.symbolicTraits, .traitBold ]
guard let boldFontDesc = fontDescriptor.withSymbolicTraits(fontDescriptorSymbolicTraits) else {
return nil
}
return UIFont(descriptor: boldFontDesc, size: pointSize)
}
}
UIFont
зҡ„pointSize
гҖӮ - Deepak DanduprolupointSize
会等于你在UIFont构造函数的size:
参数中提供的值。如果你阅读UIFont的文档,你会发现fontSize/fontOfSize方法接受或返回点大小。 - titaniumdecoy