Ios Swift切换属性字符串的下划线

时间:2017-02-22 22:15:31

标签: ios swift2 toggle underline nsmutableattributedstring

我写了两个函数给String添加下划线并删除下划线:

我想用按钮切换下划线。 那么我该如何检查NSMutableAttributedString是否具有下划线属性:

func addUlnTxtFnc(TxtPsgVal :String) -> NSMutableAttributedString
{
    let TxtRngVal = NSMakeRange(0, TxtPsgVal.characters.count)
    let TxtUnlVal = NSMutableAttributedString(string: TxtPsgVal)
    TxtUnlVal.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: TxtRngVal)

    return TxtUnlVal
}

func rmvUlnTxtFnc(TxtPsgVal :NSMutableAttributedString) -> NSMutableAttributedString
{
    let TxtRngVal = NSMakeRange(0, TxtPsgVal.string.Len())
    TxtPsgVal.removeAttribute(NSUnderlineStyleAttributeName, range: TxtRngVal)

    return TxtPsgVal
}

1 个答案:

答案 0 :(得分:2)

您可以通过调用.enumerateAttribute(attrName:, inRange:, options:, usingBlock:)上的函数NSMutableAttributedString作为参数进行检查:

func rmvUlnTxtFnc(TxtPsgVal: NSMutableAttributedString) -> NSMutableAttributedString {
    let TxtRngVal = NSMakeRange(0, TxtPsgVal.length)
    TxtPsgVal.enumerateAttribute(NSUnderlineStyleAttributeName, inRange: TxtRngVal, options: .LongestEffectiveRangeNotRequired) { attribute, range, pointer in
        if attribute != nil {
            TxtPsgVal.removeAttribute(NSUnderlineStyleAttributeName, range: range)
        }
    }
    return TxtPsgVal
}

此外,您可以将第一个功能缩短为一行:

func addUlnTxtFnc(TxtPsgVal: String) -> NSMutableAttributedString {
    return NSMutableAttributedString(string: TxtPsgVal, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
}

顺便说一句,您的代码不符合Swift社区提出的Swift style guidelines