调整导航栏标题字体大小以适合文本

时间:2016-01-20 18:23:20

标签: ios objective-c

是否可以调整导航栏标题的字体大小以适合文本?

Thnaks!

3 个答案:

答案 0 :(得分:1)

您可以创建UILabel并将其设置为UINavigationItem的titleView。请参阅Apple doc:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationItem_Class/#//apple_ref/occ/instp/UINavigationItem/titleView

对于创建的UILabel,您可以设置adjustsFontSizeToFitWidth& minimumScaleFactor属性让它适合标题。文档: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth

一些代码:

- (void)setMyTitle:(NSString *)title
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.navigationController.view.bounds.size.width - 100, 44)];
    titleLabel.text = title;
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = ...
    ...
    self.navigationItem.titleView = titleLabel;
}

答案 1 :(得分:0)

在viewDidLoad中尝试以下内容:

NSDictionary *attributes = @{ NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Bold" size:14] };

[self.navigationController.navigationBar setTitleTextAttributes:attributes];

注意:此解决方案的缺点是您必须预先知道字体大小并手动设置。我不确定您是否可以设置导航栏的标题标签以自动更改字体大小以适合文本。

修改
事实证明,您可以设置navigation bar's label to resize the font size dynamically

答案 2 :(得分:0)

快速5

private var isFirst = true
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    guard isFirst else {
    return
    }
    isFirst = false
    // Adjust Navigation Title by text
    if let navigationController = navigationController {
    let bar = navigationController.navigationBar
    var minX: CGFloat = 0
    var maxX: CGFloat = bar.bounds.width
    if let lastLeft = navigationItem.leftBarButtonItems?.last, let leftView = lastLeft.view, let buttonBarStackViewFrame = leftView.superview?.frame {
        minX = buttonBarStackViewFrame.maxX
    }
    if let firstRight = navigationItem.rightBarButtonItems?.first, let rightView = firstRight.view, let buttonBarStackViewFrame = rightView.superview?.frame {
        maxX = buttonBarStackViewFrame.minX
    }

    let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: maxX - minX, height: bar.bounds.height))
    titleLabel.text = LocStr(.favorite_master_title)
    titleLabel.adjustsFontSizeToFitWidth = true
    titleLabel.minimumScaleFactor = 0.3
    titleLabel.textColor = UIColor.white
    titleLabel.textAlignment = .center
    if UIDevice.current.modelName.contains(PLUS) {
        titleLabel.font = UIFont(name: GENERAL_FONT_NAME, size: PLUS_NAVIGATION_BAR_TITLE_FONT)!
    } else {
        titleLabel.font = UIFont(name: GENERAL_FONT_NAME, size: GENERAL_NAVIGATION_BAR_TITLE_FONT)!
    }
    navigationItem.titleView = titleLabel
    }
}

带有扩展名

extension UIBarButtonItem {
    var view: UIView? {
        return value(forKey: "view") as? UIView
    }
}