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

3

是否有可能调整导航栏标题的字体大小以适应文本内容?


您可以通过设置导航栏上的标题文本属性来实现此操作。 - Arno
好的,我应该设置哪些属性? - Balázs Vincze
3个回答

3
您可以创建一个UILabel并将其设置为UINavigationItem的titleView。 查看苹果文档: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;
}

谢谢,这正是我所发现的! - Balázs Vincze

0
在viewDidLoad中尝试以下代码:
NSDictionary *attributes = @{ NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Bold" size:14] };

[self.navigationController.navigationBar setTitleTextAttributes:attributes];

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

编辑:
事实证明,您可以将导航栏标签设置为动态调整字体大小


-2

Swift 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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接