如何在 iOS 11 中换行长大标题?

How to line break long large title in iOS 11?

我正在尝试使用 iOS 11 中的新大标题系统 Swift。当标题太长时(参见图片示例),它会添加 ... 而不是换行或缩小文本大小。如何添加换行符?

这是我用来设置标题的一些代码:

self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSForegroundColorAttributeName: MyGlobalVariable.themeMainColor]
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 22)]
navigationItem.title = "Search by Name"

试试这个:

for navItem in (self.navigationController?.navigationBar.subviews)! {
    for itemSubView in navItem.subviews {
        if let largeLabel = itemSubView as? UILabel {
            largeLabel.text = self.title
            largeLabel.numberOfLines = 0
            largeLabel.lineBreakMode = .byWordWrapping
        }
    }
}

它对我有用。

这是 Objective-C 但我使用 backButton 所做的工作。 我像这样覆盖 UIViewController 的 setTitle 方法:

-(void)setTitle:(NSString *)title{

    [super setTitle:title];

    for(id item in self.navigationController.navigationBar.subviews){

        if([item isKindOfClass:[UIView class]]){

            UIView *lc_view = (UIView *)item;

            for(id subItem in lc_view.subviews){

                if([subItem isKindOfClass:[UILabel class]]){

                    UILabel *lc_label = (UILabel *)subItem;

                    lc_label.text = self.title;
                    lc_label.numberOfLines=0;
                    lc_label.lineBreakMode = NSLineBreakByWordWrapping;
                }
            }
        }
    }

    [self.navigationController.navigationBar layoutSubviews];
    [self.navigationController.navigationBar layoutIfNeeded];
}

然后我想设置标题的地方我只是做了:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    self.title=@"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";

});

就我而言(在 UIPageViewController didFinishAnimating 方法中更改标题)似乎延迟 < 0.02 不起作用。