[英]How can I scan a string for numbers to adjust the font size in an iOS app?
I'm off to a good start. 我有一个好的开始。 But I would like to make this code more dynamic.
但我想使这段代码更具动态性。
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
UIFont *font = [UIFont systemFontOfSize:10.0f];
UIFont *smallFont = [UIFont systemFontOfSize:9.0f];
[attString beginEditing];
[attString addAttribute:NSFontAttributeName value:(font) range:NSMakeRange(0, string.length - 2)];
[attString addAttribute:NSFontAttributeName value:(smallFont) range:NSMakeRange(string.length - 1, 1)];
Say I have the following String: 说我有以下字符串:
@"C3OC2OH4" @“ C3OC2OH4”
I would like to adjust the font size of the numbers only to fulfill a chemistry application. 我只想调整数字的字体大小即可实现化学应用。 How can I scan the above string, and create a series of custom ranges to plug into my function above, which adjusts the font size?
如何扫描上面的字符串,并创建一系列自定义范围以插入到上面的函数中,从而调整字体大小?
You can enumerate the characters and apply the attributes like this. 您可以枚举字符并像这样应用属性。
NSString * string = @"C3OC2OH4";
NSMutableAttributedString * attributedString = [NSMutableAttributedString new];
NSDictionary * subscriptAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:10.0],
NSBaselineOffsetAttributeName : @(-5.0)};
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
NSCharacterSet * letterCharacterSet = [NSCharacterSet letterCharacterSet];
if ([substring rangeOfCharacterFromSet:letterCharacterSet].location != NSNotFound)
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:substring]];
else
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:substring attributes:subscriptAttributes]];
}];
In this case substring
is each character and is appended without any change if it is a letter. 在这种情况下,
substring
是每个字符,并且如果是字母,则不加任何更改地附加到substring
中。 If it is a number we change the font size and shift the baseline. 如果是数字,我们将更改字体大小并移动基线。 Change them according to your need.
根据您的需要进行更改。
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.