使用字符分隔符在Swift

时间:2015-10-31 17:11:32

标签: ios regex string swift nsrange

我之前开发了一个Android应用程序,作为用户的参考指南。它使用sqlite数据库来存储信息。数据库存储没有格式化的UTF-8文本(即粗体或带下划线的)

要突出显示所需格式的文本部分,我使用delimiter标记特别为$$括起它们,因为这不会在数据库中显示为信息。在向用户显示文本之前,我编写了一个方法来查找这些分隔符并为其中包含的文本添加格式并删除分隔符。所以$$ foo $$变成了 foo

我的java代码如下:

private static CharSequence boldUnderlineText(CharSequence text, String token) {
    int tokenLen = token.length();
    int start = text.toString().indexOf(token) + tokenLen;
    int end = text.toString().indexOf(token, start);

    while (start > -1 && end > -1)
    {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
        //add the formatting required
        spannableStringBuilder.setSpan(new UnderlineSpan(), start, end, 0);
        spannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0);

        // Delete the tokens before and after the span
        spannableStringBuilder.delete(end, end + tokenLen);
        spannableStringBuilder.delete(start - tokenLen, start);
        text = spannableStringBuilder;

        start = text.toString().indexOf(token, end - tokenLen - tokenLen) + tokenLen;
        end = text.toString().indexOf(token, start);
    }

    return text;
}

我已经在Swift for iOS中重新创建了我的应用程序,除了显示正确的格式外,它还是完整的。似乎Swift对字符串的处理方式与其他语言不同。

到目前为止,我已尝试将NSString和String类型用于原始未格式化的段落,并设法获取第一个分隔符的范围,开始和结束索引:

func applyFormatting2(noFormatString: NSString, delimiter: String){
    let paragraphLength: Int = noFormatString.length //length of paragraph
    let tokenLength: Int = delimiter.characters.count //length of token

    let rangeOfToken = noFormatString.rangeOfString(formatToken) //range of the first delimiter
    let startOfToken = rangeOfToken.toRange()?.startIndex //start index of first delimiter
    let endOfToken = rangeOfToken.toRange()?.endIndex //end index of first delimiter

    var startOfFormatting = endOfToken //where to start the edit (end index of first delimiter)



}

OR

func applyFormatting(noFormatString: String, token: String){
    let paragraphLength: Int = noFormatString.characters.count
    let tokenLength: Int = token.characters.count   //length of the $$ Token (2)
    let rangeOfToken = noFormatString.rangeOfString(formatToken)    //The range of the first instance of $$ in the no format string
    let startOfToken = rangeOfToken?.startIndex //the starting index of the found range for the found instance of $$
    let endOfToken = rangeOfToken?.endIndex //the starting index of the found range for the found instance of $$


    var startOfFormatting = endOfToken
}

我很欣赏这段代码很冗长并且有无意义的变量,但是当我解决问题时,它会帮助我思考我的代码。

我目前正在努力研究如何找到第二个/结束分隔符。我想从特定索引中搜索字符串,就像我在Java中使用行

一样
int end = text.toString().indexOf(token, start);

然而,我无法弄清楚如何使用范围来做到这一点。

任何人都可以帮我解决如何正确识别结束分隔符的位置或如何完成代码块以格式化所有必需的文本?

由于

阿尔

2 个答案:

答案 0 :(得分:5)

如何使用NSRegularExpression?

public extension NSMutableAttributedString {
    func addAttributes(attrs: [String : AnyObject], delimiter: String) throws {
        let escaped = NSRegularExpression.escapedPatternForString(delimiter)
        let regex = try NSRegularExpression(pattern:"\(escaped)(.*?)\(escaped)", options: [])

        var offset = 0
        regex.enumerateMatchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count)) { (result, flags, stop) -> Void in
            guard let result = result else {
                return
            }

            let range = NSRange(location: result.range.location + offset, length: result.range.length)
            self.addAttributes(attrs, range: range)
            let replacement = regex.replacementStringForResult(result, inString: self.string, offset: offset, template: "$1")
            self.replaceCharactersInRange(range, withString: replacement)
            offset -= (2 * delimiter.characters.count)
        }
    }
}

以下是你如何称呼它。

let string = NSMutableAttributedString(string:"Here is some $$bold$$ text that should be $$emphasized$$")
let attributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15)]
try! string.addAttributes(attributes, delimiter: "$$")

答案 1 :(得分:0)

iOS的做法是使用NS[Mutable]AttributedString。您可以在文本范围上设置属性字典。这些属性包括字体粗细,大小,颜色,行间距等。