我知道在SO上有一些关于此事的问题,我已经尝试过了,但它不起作用,这就是我现在发帖的原因。
基本上我在UIButton的titleLabel中包含一个NSDate。标签包含星期几,附加到星期几,我想在第一行显示星期几,第二行显示星期几,如下所示: / p>
然而,它一直显示在同一行:11月11日星期四
这是我在viewDidLoad中的代码:
NSMutableString *appendedDate= [NSMutableString stringWithCapacity: 20];
NSDateFormatter *nowDateFormat = [ [NSDateFormatter alloc] init];
[nowDateFormat setDateFormat:@"MM dd"];
NSDate *date = [[NSDate alloc] init];
NSString *theDateNow = [nowDateFormat stringFromDate:date];
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
[appendedDate appendString:[dateFormatter stringFromDate:[NSDate date]]];
[appendedDate appendString:@" "];
[appendedDate appendString:theDateNow];
[self.todaysDate setTitle:appendedDate forState:UIControlStateNormal];
self.todaysDate.titleLabel.numberOfLines = 0;
self.todaysDate.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
我试图缩小UIButton的宽度以查看它是否会包裹下一个单词或字符,但它仍然保持在同一行。
我怎样才能做到这一点?
答案 0 :(得分:1)
你几乎做对了。所有你需要的就是这个 [attachedDate appendString:@" \ n"]; 代替 [attachedDate appendString:@" "]; 强>
试试此代码。
NSMutableString *appendedDate= [NSMutableString stringWithCapacity: 20];
NSDateFormatter *nowDateFormat = [ [NSDateFormatter alloc] init];
[nowDateFormat setDateFormat:@"MMM dd"];
NSDate *date = [[NSDate alloc] init];
NSString *theDateNow = [nowDateFormat stringFromDate:date];
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
[appendedDate appendString:[dateFormatter stringFromDate:[NSDate date]]];
[appendedDate appendString:@"\n"];
[appendedDate appendString:theDateNow];
[self.todaysDate setTitle:appendedDate forState:UIControlStateNormal];
self.todaysDate.titleLabel.numberOfLines = 0;
CGSize buttonSize = [ self.todaysDate.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:self.todaysDate.titleLabel.font}];
self.todaysDate.frame = CGRectMake(
self.todaysDate.frame.origin.x, self.todaysDate.frame.origin.y,
self.todaysDate.frame.size.width, buttonSize.height);
注意:确保您的按钮具有足够的日期名称宽度。