在目标 C 中编写添加属性方法



嗨,我无法编写一个自定义方法,通过将字符串、int 和颜色作为参数传递来为 NSMutableAttributeString 添加属性,我在下面收到三个错误,请帮助。.

-(NSMutableAttributedString*)setAttributedSuits: (NSString*) suitString
                                   setwidth:(id)strokeWidth
                                   setColor:(id)strokeColor{
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;
}

所有给你错误的三个符号都来自UIKit。因此,这意味着您不会在 .m 文件的顶部导入 UIKit。

添加任一

#import <UIKit/UIKit.h>

@import UIKit;

到 .m 文件的顶部。

您将id用于strokeWidthstrokeColor也是没有意义的。而且看看strokeWidth是否是NSString就更没有意义了.特别是因为NSStrokeWidthAttributeName键期望NSNumber.我强烈建议您将代码更改为如下所示:

- (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;
}

当然,您需要更新 .h 文件中的声明以匹配。

最新更新