【问题标题】:write an add attribute method in objective C在目标C中编写一个添加属性方法
【发布时间】:2016-06-11 20:25:25
【问题描述】:

您好,我在编写通过传递字符串、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;
}

【问题讨论】:

    标签: objective-c methods nsmutableattributedstring


    【解决方案1】:

    所有三个给你错误的符号都来自 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文件中的声明来匹配。

    【讨论】:

    • 感谢 rmaddy 的建议,现在可以正常使用了。我对编程很陌生,有什么改进我上面代码的建议吗?非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    相关资源
    最近更新 更多