Davy ho Davy ho - 2 years ago 94
Objective-C Question

write an add attribute method in objective C

Hi I am having troubles to write an custom method for adding attributes for NSMutableAttributeString by passing strings, int, and colour as parameters, I am getting three errors below, please help..

-(NSMutableAttributedString*)setAttributedSuits: (NSString*) suitString

NSMutableAttributedString* attributeSuits = [[NSMutableAttributedString alloc]initWithString:suitString];
if ([strokeWidth isKindOfClass:[NSString class]]&&[strokeWidth isKindOfClass:[UIColor class]]) // error 1 - use of undeclared identifier "UIColor", did you mean '_color'?

[attributeSuits addAttributes:@{NSStrokeWidthAttributeName:strokeWidth, // error 2 - use of undeclared identifier "NSStrokeWidthAttributeName"
NSStrokeColorAttributeName:strokeColor} //// error 3 - use of undeclared identifier "NSStrokeColorAttributeName"
range:NSMakeRange(0, suitString.length)];


return attributeSuits;

Answer Source

All three symbols giving you the error are from UIKit. So this means you are not importing UIKit at the top of the .m file.

Add either

#import <UIKit/UIKit.h>


@import UIKit;

to the top of the .m file.

It also make no sense that you use id for the strokeWidth and strokeColor. And it makes even less sense to see if strokeWidth is an NSString. Especially since the NSStrokeWidthAttributeName key expects an NSNumber. I strongly suggest you change your code to be like this:

- (NSMutableAttributedString *)setAttributedSuits:(NSString *)suitString width:(CGFloat)strokeWidth color:(UIColor *)strokeColor {
    NSDictionary *attributes = @{
        NSStrokeWidthAttributeName : @(strokeWidth),
        NSStrokeColorAttributeName : strokeColor

    NSMutableAttributedString *attributeSuits = [[NSMutableAttributedString alloc] initWithString:suitString attributes:attributes];

    return attributeSuits;

Of course you need to update the declaration in the .h file to match.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download