Objective c 在字符串中填充空格
以下问题最好针对目标C(Swift也可以)。如何使我的字符串看起来像下图中的字符串?分母和百分比部分的右括号需要对齐。很明显,百分比可以是100%,0%,0%,这意味着左括号中的百分比不会对齐,这很好。百分比部分所需的空间量为9个点Objective c 在字符串中填充空格,objective-c,string,nsstring,Objective C,String,Nsstring,以下问题最好针对目标C(Swift也可以)。如何使我的字符串看起来像下图中的字符串?分母和百分比部分的右括号需要对齐。很明显,百分比可以是100%,0%,0%,这意味着左括号中的百分比不会对齐,这很好。百分比部分所需的空间量为9个点 我强烈建议您使用布局引擎来实现这些功能,但您可以使用以下类似的东西来模拟自己,我还没有测试过 // given a prefix, like @"5/50" and a suffix like @"(80%)", return a string where they
我强烈建议您使用布局引擎来实现这些功能,但您可以使用以下类似的东西来模拟自己,我还没有测试过
// given a prefix, like @"5/50" and a suffix like @"(80%)", return a string where they are combined
// add leading spaces so that the prefix is right-justified to a particular pixel position
//
- (NSString *)paddedPrefix:(NSString *)prefix andSuffix:(NSString *)suffix forLabel:(UILabel *)label {
// or get maxWidth some other way, depends on your app
CGFloat maxWidth = [self widthOfString:@"88888/50" presentedIn:label];
NSMutableString *mutablePrefix = [prefix mutableCopy];
CGFloat width = [self widthOfString:mutablePrefix presentedIn:label];
while (width<maxWidth) {
[mutablePrefix insertString:@" " atIndex:0];
}
// the number of blanks between the prefix and suffix is also up to you here:
return [NSString stringWithFormat:@"%@ %@", mutablePrefix, suffix];
}
// answer the width of the passed string assuming an infinitely wide label (no wrapping)
//
- (CGFloat)widthOfString:(NSString *)string presentedIn:(UILabel *)label {
NSAttributedString *as = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:label.font}];
CGRect rect = [as boundingRectWithSize:(CGSize){CGFLOAT_MAX, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return rect.size.width;
}
//给定前缀,如@“5/50”和后缀,如@“(80%)”,返回它们组合的字符串
//添加前导空格,使前缀右对齐到特定像素位置
//
-(NSString*)填充前缀:(NSString*)前缀和后缀:(NSString*)标签后缀:(UILabel*)标签{
//或者通过其他方式获取maxWidth,具体取决于您的应用程序
CGFloat maxWidth=[字符串的自宽度:@“88888/50”显示在:标签中];
NSMutableString*mutablePrefix=[前缀mutableCopy];
CGFloat width=[self-widthOfString:mutablePrefix-presentedIn:label];
while(widthStrings)通过UILabels使用户可见。您可以通过在代码或IBSure中排列6个标签来实现这一点,但是如何使用每行一个字符串来实现呢?如果将UILabel设置为右对齐会怎么样?假设第一个值为50/50和(100%),那么其余的将不会对齐。每行只使用两个标签即可。