[英]NSMutableAttributedString Crashing App
I'm doing something wrong with the range (I think) in setting this NSMutableAttributedString
. 我在设置此NSMutableAttributedString
的范围(我认为)上做错了。 Can anyone tell me why this is crashing my program? 谁能告诉我为什么这会使我的程序崩溃? It looks right to me, but I'm obviously wrong! 对我来说看起来不错,但我显然错了! Thanks. 谢谢。
NSString *placeHolderString = @"USERNAME";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
float spacing = 5.0f;
// crashes on this line
[attributedString addAttribute:NSKernAttributeName
value:@(spacing)
range:NSMakeRange(0, [placeHolderString length])];
self.userNameTextField.attributedPlaceholder = attributedString;
What I think was causing your issue is that you were never really accounting for your placeholderString
in the first place. 我认为造成您的问题的原因是,您从未真正考虑过placeholderString
。 In addition, your value parameter could simply use numberWithFloat
as the application would then known what type you are using all the time. 另外,您的value参数可以简单地使用numberWithFloat
因为应用程序随后将始终知道您使用的是哪种类型。
Once you account for the placeHolderString
, you are then going to use the length for the attributeString
, as it now just contains the contents of your placeholderString
. 一旦考虑了placeHolderString
, placeHolderString
使用attributeString
的长度,因为它现在仅包含placeholderString
的内容。 Then we just simply copy that string which contains your attribute using the UITextField
property attributedText
. 然后,我们只需使用UITextField
属性attributedText
复制包含您的属性的字符串。
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:placeHolderString];
float spacing = 5.0f;
[attributeString addAttribute:NSKernAttributeName
value:[NSNumber numberWithFloat:spacing]
range:(NSRange){0,[attributeString length]}];
userNameTextField.attributedText = [attributeString copy];
For more context, attributes like NSUnderlineStyleAttributeName
exist and you can do some really powerful things with NSMutableAttributedString
. 对于更多上下文,存在诸如NSUnderlineStyleAttributeName
属性,您可以使用NSMutableAttributedString
进行一些真正强大的操作。 Refer to the documentation for options. 有关选项,请参阅文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.