简体   繁体   English

iOS Swift Toggle属性字符串的下划线

[英]Ios Swift Toggle underline of attributed string

I hav written two fuction to Add underline to a String and remove underline : 我已经写了两个函数来向字符串添加下划线并删除下划线:

I want to toggle underline with a button. 我想使用按钮切换下划线。 So how do I check if NSMutableAttributedString has underline attribute : 因此,如何检查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
}

You can check by calling the function .enumerateAttribute(attrName:, inRange:, options:, usingBlock:) on the NSMutableAttributedString you get in as the parameter: 您可以通过对作为参数进入的NSMutableAttributedString调用函数.enumerateAttribute(attrName:, inRange:, options:, usingBlock:)进行检查:

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
}

Also, you can shorten your first function to a single line: 另外,您可以将第一个功能缩短为一行:

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

As an aside, your code does not conform to the Swift style guidelines proposed by the Swift community. 顺便说一句,您的代码不符合Swift社区提出的Swift样式准则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM