Search code examples
iosobjective-cnsattributedstringnsmutableattributedstring

Changing NSAttributedString text value for a UIControl


Currently all my buttons and textfields have attributedText values defined to be attributed strings.

Consider the case with a simple UILabel. Whenever I have to change the text for this UILabel (based on some user action), I have to redefine the attributes on the NSAttributedString. One way is to simply create a subroutine that generates these attributes whenever I require them but that's a concern given there could be a number of different labels (or attributed strings) that would require such convenience methods.

Another could be simply changing the text field and having observers add those attributes but that's the same amount of work and now probably more complicated.

Is there a simple way of achieving the above without redefining attributes?


Solution

  • Exploring @Harry's ideas, here are a few ideas :

    Category on NSAttributedString, category on UILabel, or category on NSDictionary, and maybe a mix of them, according to which one best suits you and your project. Using a category on NSAttributedString in priority before UILabel could be more interesting in case you wanted to use the custom NSAttributedString for others kind of object (like a UITextView).

    A good start:

    typedef enum : NSUInteger {
        AttributeStyle1,
        AttributeStyle2,
    } AttributeStyles;
    

    A possible category method on NSDictionary:

    -(NSDictionary *)attributesForStyle:(AttributeStyles)style
    {
        NSDictionary *attributes;
        switch(style)
        {
            case AttributeStyle1:
                attributes = @{}//Set it
                break;
            case AttributeStyle2:
                attributes = @{}//Set it
                break;
            default:
                attributes = @{}//Set it
                break;
        }
        return attributes;
    }
    

    Category possible on UILabel:

    -(void)setString:(NSString *)string withAttributes:(NSDictionary *)attributes
    {
        [self setAttributedText:[[NSAttributedString alloc] initWithString:string attributes:attributes];
    }
    

    Category possible on NSAttributedString:

    -(NSAttributedString  *)initWithString:(NSString *)string withStyle:(AttributedStyles)style
    {
        //Here, a mix is possible using the first method, or doing here the switch case
        //Ex:  return [[NSAttributedString alloc] initWithString:string attributes:[NSDictionary attributesForStyle:style];
        //And to use like this: [yourLabel setAttributedText:[[NSAttributedString alloc] initWithString:string withStyle:AttributeStyle1];
    }