简体   繁体   中英

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 :

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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