I want to change only the UILabel string, leaving the attributes set in the storyboard.

Asked 2 years ago, Updated 2 years ago, 127 views

https://stackoverflow.com/a/42166899/1979953
and
https://stackoverflow.com/a/38297423/1979953

with reference to
extension UILabel {
    func replaceAttributedText(string:String){
        iflet originalAttributedText=self.attributedText{
            let attributes=originalAttributedText.attributes(at:0, effectiveRange:nil)
            self.attributedText=NSAttributedString(string:string, attributes:attributes)
        }
    }
}

I tried to create , but after giving empty,

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEarray objectAtIndex:effectiveRange::Out of bounds'

will be

In other words,

self.hogeLabel.replaceAttributedText (string: "hoge")
self.hogeLabel.replaceAttributedText(string:"")
self.hogeLabel.replaceAttributedText(string: "aaa") // Error after giving empty characters

These codes cause an error.

I guess it's because the attribute information was blown away by giving empty characters, but is there any way to replace only the strings?

(I would like to include empty instead of empty but empty instead of empty)

swift ios

2022-09-30 21:41

1 Answers

As I commented, the current implementation of NSAttributeString does not accept the listed extension (assuming you want to substitute an empty string).

Here's a custom label class that allows you to "remove the attributes you set on the storyboard and change only the strings" as one of the "other ways."

import UIKit

classAttrLabel:UILabel {
    // Instance property that stores the attributes set in the storyboard
    var attributes: [NSAttributedString.Key:Any] = [:]

    override funcawakeFromNib(){
        // Save attributes set when instantiated from Xib/Storyboard
        iflet attrText=self.attributedText, attrText.length>0 {
            attributes=attrText.attributes(at:0, effectiveRange:nil)
        }
    }

    // If you manipulate the `text` property, use the saved attribute to change only the string
    override var text:String?{
        get{
            return super.text
        }
        set {
            self.attributedText=NSAttributedString(string:newValue???",
                                                     attributes:self.attributes)
        }
    }
}

You can use it immediately by replacing the Custom Class of the label you normally placed on the storyboard with AttrLabel above.

At least for this simple example

self.hogeLabel.text="hoge"
        self.hogeLabel.text=""
        self.hogeLabel.text="aaa"

You can see that you can only replace the string while saving the original attribute.

If you think about what you really want to do and think about it without being bound by one way, there might be a better way.Try this and that, including the example above.


2022-09-30 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.