我试图制作一个UILabel"填满"从底部。我的意思是(如果有换行符号)我希望在标签的第二行有尽可能长的金额,而不是在第一行。以下是我的故事板中的默认行为:
以下是我想要发生的事情:
这可能吗?如果是这样,我将如何做到这一点。我使用swift并安装了可可豆荚,所以如果你有一个允许我这样做的框架的建议,我很乐意这样做,虽然我还没有找到任何通过搜索。提前谢谢!
答案 0 :(得分:2)
听起来你可能不得不亲自编写分线功能。 在字符串中向后工作,直到找到空格,用现有单词+这个新单词创建一个临时字符串,根据窗口宽度测量字符串,如果它太大,则在那里放一个新行并再次开始一个新行。
答案 1 :(得分:2)
如果您仍在努力完成任务,这里是我的相同代码。希望它有所帮助:)
只需将以下类添加到项目中即可。
CustomLabel.h
#import <UIKit/UIKit.h>
@interface CustomLabel : UILabel
@end
CustomLabel.m
#import "CustomLabel.h"
@implementation CustomLabel
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.numberOfLines = 0;
}
return self;
}
-(NSString *) getManipulatedString: (NSString *)text {
NSString *reverseString = [self getReverseString:text];
NSArray *arrayOfReverseString = [reverseString componentsSeparatedByString:@" "];
NSString *finalReverseString = @"";
for (NSString *word in arrayOfReverseString) {
NSString *tempString = finalReverseString;
tempString = [tempString stringByAppendingString:[NSString stringWithFormat:@"%@ ", word]];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGRect labelRect = [tempString boundingRectWithSize:CGSizeMake(screenWidth, 10000)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : self.font
}
context:nil];
if (labelRect.size.width > self.frame.size.width) {
finalReverseString = [finalReverseString stringByAppendingString:[NSString stringWithFormat:@"\n%@ ", word]];
} else {
finalReverseString = tempString;
}
}
NSArray *arrayOflines = [self getReverseOfArray:[finalReverseString componentsSeparatedByString:@" \n"]];
NSString *finalString = @"";
for (NSString *lineString in arrayOflines) {
NSString *reverse = [self getReverseString:lineString];
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:@"%@\n",reverse]];
}
NSLog(@"%@", finalString);
return [[finalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
- (NSString *)getReverseString:(NSString *)string {
NSArray *arrayOfWords = [string componentsSeparatedByString:@" "];
NSString *reverseString = [[self getReverseOfArray:arrayOfWords] componentsJoinedByString:@" "];
return reverseString;
}
- (NSArray *)getReverseOfArray: (NSArray *)array {
NSMutableArray *reversed = [NSMutableArray arrayWithCapacity:[array count]];
NSEnumerator *enumerator = [array reverseObjectEnumerator];
for (id element in enumerator) {
[reversed addObject:element];
}
return reversed;
}
- (void)setText:(NSString *)text {
NSString *string = [self getManipulatedString:text];
[super setText:string];
[self sizeToFit];
}
@end
要使用它,您只需添加以下行,即可完成:)
CustomLabel *label = [[CustomLabel alloc] initWithFrame:CGRectMake(10, 100, 210, 100)];
label.text = @"This is a test for aa next aa aa alignment from bottom tadadada tatadad";
您获得以上代码的以下输出: