如何快速防止标签中的孤儿? [英] How can I prevent orphans in a label in swift?

查看:19
本文介绍了如何快速防止标签中的孤儿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以有一两行的标签.如果它有两行,我希望第二行至少有两个(或三个)词,而不是一个.关于如何使用 swift 实现这一目标的任何想法?

I have a label that can have one or two lines. If it has two lines, I want the second line to have at least two (or maybe three) words, never just one. Any ideas about how I can accomplish that using swift?

提前致谢!

丹尼尔

我删除了我最初的愚蠢想法,这些想法并没有真正帮助.

I edited out my silly first thoughts that didn't really help.

推荐答案

好吧,看了很多遍之后,我想出了我认为最好的解决方案.

Ok, after looking around a lot I came up with what I think is the best solution.

我写了这个函数:

func numberOfLinesInLabelForText(text: String) -> Int {

    let attributes = [NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)]
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let labelSize = text!.boundingRectWithSize(CGSizeMake((screenSize.width - 30), CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)

    let lines = floor(CGFloat(labelSize.height) / bookTitleLabel.font.lineHeight)
    return Int(lines)
}

您输入将显示在标签中的字符串,它会告诉您标签将有多少行.我正在为此特定标签使用动态类型和标题样式,因此使用 preferredFontForTextStyle(UIFontTextStyleHeadline) 部分,但您可以将其更改为标签使用的字体和大小.然后我使用 (screenSize.width - 30) 作为我标签的宽度,因为它的宽度不是固定的,所以我使用屏幕尺寸减去前导和尾随.这可能不是最优雅的解决方案,我愿意接受更好的建议.剩下的就很简单了.

You put in the string that will be displayed in the label and it gives you how many lines the label will have. I'm using dynamic type and the Headline style for this particular label, hence the preferredFontForTextStyle(UIFontTextStyleHeadline) part, but you can change that to the font and size your label uses. Then I use (screenSize.width - 30) for my label's width because it's width is not fixed, so I'm using the screen size minus leading and trailing. This is probably not the most elegant solution, I'm open to better suggestions. The rest is pretty straightforward.

在获得行数后,我可以执行此操作:

After I have the number of lines I can do this:

func splittedString(text: String) -> String {

    if numberOfLinesInLabel(text) == 2 {
        var chars = Array(text.characters)
        var i = chars.count / 2
        var x = chars.count / 2
        while chars[i] != " " && chars[x] != " " {
            i--
            x++
        }
        if chars[i] == " " {
            chars.insert("\n", atIndex: i+1)
        } else {
            chars.insert("\n", atIndex: x+1)
        }
        return String(chars)
    }
}

我决定在最接近字符串一半的断点处将字符串一分为二,而不是仅仅避免孤儿,这就是最后一个函数的作用,但调整它以满足您的需求并不难.

Instead of just avoiding orphans I decided to split the string in two at the breaking point nearest to its half, so that's what this last function does, but it wouldn't be hard to tweak it to suit your needs.

这就给你了!

这篇关于如何快速防止标签中的孤儿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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