2017-06-05 44 views
1

我需要在我的應用程序中使用iOS的系統字體「Hiragino Sans W3」,但無論我選擇哪種尺寸/樣式或UILabel的尺寸,字體的上行字母和下行總是出現削波:系統字體「Hiragino Sans」與修剪上升和下行顯示

enter image description here

看來,這可以在此固定通過創建UILabel一個子類,覆蓋方法textRectForBounds:limitedToNumberOfLines:返回「正確」的價值。所以下面的代碼...

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines 
{ 
    CGRect result = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; 
    result = CGRectInset(result, 0, -5); 
    return result; 
} 

...結果在上升段和下行都沒有再剪短

enter image description here

我知道它也可以調整字體伸和下伸位置使用外部編輯器。 但是這是一個系統字體,它不應該沒有任何修改正確工作?有什麼我在這裏失蹤?

在此先感謝您的任何答案。

+1

我希望我對你有一個更好的答案,但我只能說我能夠重現這一點,並同意這是意想不到的。您可能想要向Apple提交錯誤報告。 – allocate

回答

1

我認爲這個問題真的歸結爲字體本身(「Hiragino Sans」)。使用字體編輯器可以看到字形超出上行和下行值,這是iOS似乎假設爲顯示文本的垂直「邊界框」。

對於缺乏更好的解決方案,我一直在使用一個(非常醜陋的)破解修改UIFont只讀屬性ascenderlineHeight的值。

文件UIFont+Alignment.h

#import <UIKit/UIKit.h> 

@interface UIFont (Alignment) 

- (void)ensureCorrectFontAlignment; 

@end 

文件UIFont+Alignment.m

#import "UIFont+Alignment.h" 
#import <objc/runtime.h> 
#import <objc/message.h> 

static NSHashTable *adjustedFontsList; 

@implementation UIFont (Alignment) 

- (void)ensureCorrectFontAlignment 
{ 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     adjustedFontsList = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory]; 
    }); 

    @synchronized (adjustedFontsList) { 

     if ([adjustedFontsList containsObject:self]) { 
      return; 
     } 
     else if ([self.fontName containsString:@"Hiragino"]) { 

      SEL originalAscenderSelector = @selector(ascender); 
      Method originalAscenderMethod = class_getInstanceMethod([UIFont class], originalAscenderSelector); 
      SEL originalLineHeightSelector = @selector(lineHeight); 
      Method originalLineHeightMethod = class_getInstanceMethod([UIFont class], originalLineHeightSelector); 

      id result = method_invoke(self, originalAscenderMethod, nil); 
      CGFloat originalValue = [[result valueForKey:@"ascender"] floatValue]; 
      [result setValue:@(originalValue * 1.15) forKey:@"ascender"]; 

      result = method_invoke(self, originalLineHeightMethod, nil); 
      originalValue = [[result valueForKey:@"lineHeight"] floatValue]; 
      [result setValue:@(originalValue * 1.25) forKey:@"lineHeight"]; 

      [adjustedFontsList addObject:self]; 
     } 
    } 
} 

@end 

要申請,只需輸入標題和創建一個新的字體實例後調用[myUIFont ensureCorrectFontAlignment]