I'm using Swift 4, with Xcode 9.2.
I have a UILabel, which in their .attributedText property I have associated an NSMutableAttributedString. In fact, this NSMutableAttributedString is made from the concatenation of two different NSMutableAttributedString, everyone with different attributes.
Since using append() I merge all NSMutableAttributedString in a single mutable string, how can I retrieve the range of the attributes I have previously set before appending everything (probably it can't be done)? Or, there is a way to place more than a NSMutableAttributedString inside the UILabel.attributedText? Or, again, can I get this behaviour without using a UILabel (maybe using a UITextView, for example)?
This is the problem I encountered because I need to add a UISwitch that hides (= restore it to default black) and shows again the foregroundColor of this NSMutableAttributedString on the go, but since only a part of this string has a foregroundColor attribute, I can't simply apply the attribute on the whole string.
This is the code:
func attributedTest (_ testString : String)
{
// the first NSMutableAttributedString created
let firstString = NSMutableAttributedString(
string: testString,
attributes: [NSAttributedStringKey.font : UIFont(
name: "Futura",
size: 20.0)!])
// the second NSMutableAttributedString created, they're equal
let secondString = NSMutableAttributedString(
string: testString,
attributes: [NSAttributedStringKey.font : UIFont(
name: "Futura",
size: 20.0)!])
// here I'm adding the attributed on test2
// the NSRange, in this case, is equal to the whole string
secondString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRangeFromString("0, \(testString.count)"))
// here I'm appending the second string to the first one
firstString.append(secondString)
// here I'm setting the testLabel.attributedText
testLabel.attributedText = test
}
I thought of a plain copy of this NSMutableAttributedString, with no attributes at all (the UIFont is external to the attribute so I'm not worried), stored somewhere. Can having these two strings and switch them on the go when needed through the UISwitch be a decent solution (not optimal, though)?
Thank you!