簡體   English   中英

如何向UILabel添加自定義字體,但標簽會從故事板中保留其大小

[英]How to add custom font to UILabel but have label retain its size from storyboard

我目前正在將UILabel子類化為將字體更改為自定義字體,但我還希望它保留我在每個標簽的故事板中設置的大小。 是否有這樣做的方法,並檢測當前選擇的樣式粗體等,並盡可能用相關的自定義字體替換它?

這是我用來設置當前字體的代碼。

- (id)initWithCoder:(NSCoder *)coder {
 self = [super initWithCoder:coder];
 if (self) {
    self.font = [UIFont fontWithName:@"FrutigerLT-Roman" size:17.0];
  }
  return self;
}

要向您的應用添加自定義字體,請查看以下鏈接: http//shang-liang.com/blog/custom-fonts-in-ios4/

現在,為了保持故事板中的大小設置,應該沒問題:

self.font = [UIFont fontWithName:@"FrutigerLT-Roman" size:self.font.pointSize];

最后我寫了自己的解決方案。

https://stackoverflow.com/a/12281017/1565615 @Nathan R.幫助我獲取字體大小。

然后我提取了UIFont描述的font-weight組件並相應地改變了字體,這對於自定義字體來說很好,因為現在我可以在storyboard中設置字體大小和樣式,它將在UILabel的子類型中設置。

我希望有一種更簡單的方法來識別正在使用的font-weight類型,如font.fontWeight我意識到我的解決方案是longwinded但它可以工作任何進一步的想法將是有用的。

- (id)initWithCoder:(NSCoder *)coder
{
  self = [super initWithCoder:coder];
  if (self)
  {
    NSString *fontInfo = self.font.description;//Complete font description
    NSArray *splitUpFontDescription = [fontInfo componentsSeparatedByString: @";"];//Split up
    NSString *fontWeight = [[NSString alloc]init];
    for (NSString *tempString in splitUpFontDescription)
    {
      if ([tempString rangeOfString:@"font-weight"].location != NSNotFound)//Font weight found
      {
        fontWeight = [tempString stringByReplacingOccurrencesOfString:@" "
                                                  withString:@""];//Remove whitespace
        fontWeight = [fontWeight stringByReplacingOccurrencesOfString:@"font-weight:"
                                                           withString:@""];
      }
    }
    NSLog(@"Font style (Weight) = *%@*",fontWeight);
    if ([fontWeight isEqualToString:@"normal"])
    {
      //Set to custom font normal.
      self.font = [UIFont fontWithName:@"FrutigerLT-Roman" size:self.font.pointSize];
    }
    else if([fontWeight isEqualToString:@"bold"])
    {
      //Set to custom font bold.
      self.font = [UIFont fontWithName:@"FrutigerLT-Bold" size:self.font.pointSize];
    }
  }
  return self;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM