以特定方式将String转换为NSAttributedString [英] convert a String to NSAttributedString in a specific manner

查看:167
本文介绍了以特定方式将String转换为NSAttributedString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个看起来像这样的字符串:Swift , VisualBasic , Ruby

so i have a String which looks like this : Swift , VisualBasic , Ruby

我想将此字符串转换为如下形式:

i wanna convert this string to something like this :

基本上,我想在单个单词后面创建背景,是的,我可以使用NSTokenField库来获得此行为,但是我的文本不是由用户手动输入的,它是预先构造好的(从数组中输入的),我不希望这样的整个行为NSTokeField我只想要这样的外观和选择(通过选择,我指的是一次按一下Backspace即可清除一个单词,整个单词而不是字母)

basically i wanna create a background behind a single word , yeah i can use the NSTokenField libraries for getting this behaviour but my text is not manually entered by user its pre structured (from an array) and i dont want the whole behaviour of NSTokeField i just want the appearance like this and selection (by selection i mean to clear a word at one single tap on backspace , the whole word not a letter )

好吧,我知道如何更改文本的颜色

well i know how to change the colour of a text something like this

   func getColoredText(text: String) -> NSMutableAttributedString {
    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    let words:[String] = text.componentsSeparatedByString(" ")
    var w = ""

    for word in words {
        if (word.hasPrefix("{|") && word.hasSuffix("|}")) {
            let range:NSRange = (string.string as NSString).rangeOfString(word)
            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
            w = word.stringByReplacingOccurrencesOfString("{|", withString: "")
            w = w.stringByReplacingOccurrencesOfString("|}", withString: "")
            string.replaceCharactersInRange(range, withString: w)
        }
    }
    return string
}

但是,如果有人可以向我提供一些指导,那么我不知道如何实现自己的目标,那么它将对我有很大帮助

but i dont know how to achieve what i want if somebody can provide me some guidance then it'll be so helpful for me

请注意,如果我的问题不够清楚,请告诉我,我将添加更多详细信息

P.s if my question is not clear enough then please let me know i'll add some more details

推荐答案

如果想弄圆角,只使用几个UILabel会容易得多.

It's going to be much easier to just use several UILabels if you want to get rounded corners.

如果可以接受,您可以首先生成一个属性字符串数组,例如:

If that's acceptable you can first generate an array of attributed strings like:

func getAttributedStrings(text: String) -> [NSAttributedString]
{
    let words:[String] = text.componentsSeparatedByString(" , ")

    let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSBackgroundColorAttributeName: UIColor.blueColor()]

    let attribWords = words.map({
        return NSAttributedString(string: " \($0) ", attributes: attributes)
    })
    return attribWords
}

对于每个属性字符串,我们需要创建UILabel.为此,我们可以创建一个传递NSAttributedString并返回UILabel的函数:

For each attributed string we need to create UILabel. To do so we can create a function that passes in an NSAttributedString and returns a UILabel:

func createLabel(string:NSAttributedString) ->UILabel
{
    let label = UILabel()
    label.backgroundColor = UIColor.blueColor()
    label.attributedText = string
    label.sizeToFit()
    label.layer.masksToBounds = true
    label.layer.cornerRadius = label.frame.height * 0.5
    return label
}

现在,我们将通过输入以下内容将输入字符串转换为标签:

Now we'll convert our input string into labels by saying:

let attribWords = getAttributedStrings("Java , Swift , JavaScript , Objective-C , Ruby , Pearl , Lisp , Haskell , C++ , C")
let labels = attribWords.map { string in
        return createLabel(string)
    }

现在我们只需要在视图中显示它们:

Now we just need to display them in a view:

let buffer:CGFloat = 3.0
var xOffset:CGFloat = buffer
var yOffset:CGFloat = buffer

let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 320.0, height: 400.0))
view.backgroundColor = UIColor.lightGrayColor()


for label in labels
{
    label.frame.origin.x = xOffset
    label.frame.origin.y = yOffset

    if label.frame.maxX > view.frame.maxX
    {
        xOffset = buffer
        yOffset += label.frame.height + buffer

        label.frame.origin.x = xOffset
        label.frame.origin.y = yOffset
    }

    view.addSubview(label)
    xOffset += label.frame.width + buffer
}

在这一点上,我们还可以通过说出以下内容来调整标签的高度:

We can also at this point resize our view to the height of the labels by saying:

if let labelHeight = labels.last?.frame.height
{
    view.frame.height = yOffset + labelHeight + buffer
}

将此代码扔到一个快速的操场上会导致:

Throwing this code in a swift playground results in:

如果您不能使用标签,例如,如果您想要可编辑的UITextView,我会舍弃圆角,而只说类似以下内容:

If you can't use labels, if you want an editable UITextView for example, I would give up on rounded corners and just say something like:

let attribWords = getAttributedStrings("Java , Swift , JavaScript , Objective-C , Ruby , Pearl , Lisp , Haskell , C++ , C")
let attribString = NSMutableAttributedString()
attribWords.forEach{
    attribString.appendAttributedString(NSAttributedString(string: "  "))
    attribString.appendAttributedString($0)
}
textView.attributedText = attribString

这篇关于以特定方式将String转换为NSAttributedString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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