簡體   English   中英

如何在多行上顯示UIButton標簽?

[英]How to display a UIButton label on multiple lines?

我知道在SO上對此有一些疑問,我已經嘗試過了,但是沒有用,這就是為什么我現在要發布。

基本上,我在UIButton的titleLabel中包含一個NSDate。 標簽包含包含“星期幾”,並附加到“星期幾”,我想在第一行顯示“星期幾”,在第二行顯示“星期幾”,如下所示:

在此處輸入圖片說明

但是,它始終顯示在同一行上: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);

注意:確保您的按鈕具有足夠的寬度以用作“日期”名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM