gpt4 book ai didi

ios - 如何在多行上显示 UIButton 标签?

转载 作者:行者123 更新时间:2023-11-29 12:32:49 26 4
gpt4 key购买 nike

我知道在 SO 上有一些关于此的问题,我已经尝试过但没有用,这就是我现在发帖的原因。

基本上,我在 UIButton 的 titleLabel 中包含一个 NSDate。标签包含包含星期几,附加到星期几,我想在第一行显示星期几,在第二行显示星期几,如下所示:

enter image description here

但是,它一直显示在同一行:Thursday 11 27

这是我在 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 的宽度以查看它是否会换行下一个单词或字符,但它仍然保持在同一行上。

我怎样才能做到这一点?

最佳答案

你几乎做对了。你只需要这个 [appendedDate appendString:@"\n"];代替 [appendedDate 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);

注意:确保您的按钮有足够的宽度来显示日期名称。

关于ios - 如何在多行上显示 UIButton 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27178770/

26 4 0