Search code examples
iosswift2toggleunderlinensmutableattributedstring

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
}

Solution

  • 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.