Just a Computer Graphics Studio & My Life

[iOS] 動態框架 (Dynamic Frame)

不知怎麼稱呼,就先叫做動態框架 (Dynamic Frame)吧!描述一下我想達到的效果,簡單來說就是根據文字多寡,來讓顯示的界面可以跟著調整,最後所想要呈現的字不會被介面擋到。

因為很多時候是不知道字數的多寡,通常是在運行的時候才會知道,特別是從網路上取得的資料,此時我們會想要做這件事。

我在給剛進研究所的學生的話文章找了一串描述:

“Write something every day.” This is the advice I learned from Prof. Fred Brooks at UNC. In college entrance exams, your achievement was measured by the sum of your scores in various subjects, like Math, English, Physics, Chemistry, and Chinese. A fallacy in that scheme is that you could improve your ranking by working on one subject alone. However, in the graduate school (and beyond), you may find that your achievement is measured by a mysterious equation that is more like the product (i.e. multiplication) of your hard work in solving the problem (e.g. research and implementation) and your technical writing and presentation. You get no credit if you have solved a extremely hard problem and tell no one.

在Xcode上IB設計是這樣:

動態框架 Dynamic Frame

/**
 Theme: Dynamic Frame
 IDE: Xcode 6
 Language: Objective C
 Date: 104/04/23
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    CGSize textSize = {self.happyTextView.frame.size.width, 10000.0};
    NSMutableParagraphStyle *pstyle = [[NSMutableParagraphStyle alloc] init];
    pstyle.lineBreakMode = NSLineBreakByWordWrapping;
    CGRect textRect = [self.happyTextView.text
                       boundingRectWithSize:textSize
                       options:NSStringDrawingUsesLineFragmentOrigin
                       attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14.0f], NSParagraphStyleAttributeName: pstyle}
                       context:nil];
    CGSize size = textRect.size;

    self.happyTextView.frame = CGRectMake(self.happyTextView.frame.origin.x, self.happyTextView.frame.origin.y, size.width, size.height + 50);
}

編譯執行後呈現如此:

動態框架 Dynamic Frame2

這裡特別要注意的是,我試過在viewDidLoad和viewWillAppear執行,不過最後都沒有動靜,只有在viewDidAppear才有效果!這個特性跟Auto Layout很像呢!

參考:sizeWithFont method is deprecated. boundingRectWithSize is returning wrong valuesiOS7中UILabel高度調整注意事項

廣告

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: