UILabel文本截断与文本中的换行符 [英] UILabel text truncation vs. line breaks in text

查看:187
本文介绍了UILabel文本截断与文本中的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UILabel,它作为titleView放置在导航栏中.我希望它有2行,第一行可以截断,第二行居中对齐.

I have a UILabel that is put as titleView in the navigation bar. I want it to have 2 lines, where the first line can be truncated and the second is center aligned.

在代码中看起来更像这样:

In code it looks more less like this:

    let label = UILabel()
    let text = NSAttributedString(string: "Long long long text\nsecond line")
    label.attributedText = text
    label.textAlignment = .Center
    label.numberOfLines = 0
    label.lineBreakMode = .ByTruncatingTail
    label.sizeToFit()

    self.navigationItem.titleView = label

第一行文字不超过可用效果 空间是这样的:

The effect in case of the first line text is not exceeding available space is like this:

这很好,但是当第一行文字的长度大于:

It's pretty good, but when the first line text is longer than:

let text = NSAttributedString(string: "Very very very very very long text\nsecond line")

我想实现以下目标.

I want to achieve like below.

如何完成?我尝试了numberOfLines和lineBreakMode,但是没有用.

How it can be done? I experimented with numberOfLines and lineBreakMode but it's not worked.

推荐答案

将您的换行模式更改为ByTruncatingMiddle而不是ByTruncatingTail.像下面这样

change your line breakmode to ByTruncatingMiddle instead of ByTruncatingTail. Something like below,

    label.lineBreakMode = .ByTruncatingMiddle

希望这会有所帮助:)

这篇关于UILabel文本截断与文本中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆