不知怎麼稱呼,就先叫做動態框架 (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設計是這樣:
/** 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); }
編譯執行後呈現如此:
這裡特別要注意的是,我試過在viewDidLoad和viewWillAppear執行,不過最後都沒有動靜,只有在viewDidAppear才有效果!這個特性跟Auto Layout很像呢!
參考:sizeWithFont method is deprecated. boundingRectWithSize is returning wrong values、iOS7中UILabel高度調整注意事項。
Comments on: "[iOS] 動態框架 (Dynamic Frame)" (1)
[…] 我們一定使用過通訊App,輸入框會隨著字數多換行而高度變大。四年前我寫過文章:動態框架 (Dynamic Frame),這次我要來講進階用法,就是邊打字邊算輸入框的高度:TextView 動態高度 (TextView Dynamic Height)。 […]
讚讚