简体   繁体   中英

How to display a UIButton label on multiple lines?

I know there are some questions regarding this on SO, and I've tried them but it doesn't work, which is why I'm posting now.

Basically I have an NSDate contained within the titleLabel of a UIButton. The label contain contains the Day of the Week, appended to the Date of the Week, and I'm wanting to display the Day of the Week on the first line, and Date of the Week on the second line like so:

在此处输入图片说明

However, it keeps displaying on the same line: Thursday 11 27

Here's my code in 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;

I've tried to shrink the width of the UIButton to see if it would wrap the next word or character, but it still remains on the same line.

How can I achieve this?

You almost got it right. All you needed is this [appendedDate appendString:@"\\n"]; in the place of [appendedDate appendString:@" "];

try this Code.

    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);

NOTE: Make sure your button has enough width for Day name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM