問題描述
我試圖將 UITextView 放置在帶有 AutoLayout 的 UIScrollView 中,但沒有成功.我試過的是,
I am trying to place UITextView inside UIScrollView with AutoLayout with no luck. What I have tried is,
- 我將 UIScrollView 放在 Storyboard 的主視圖中
- 我在 Storyboard 中的 UIScrollView 中放置了 UITextView 并禁用了 Scrolling Enabled
- 我在 UIScrollView 上設置了約束(前導、尾隨、頂部、底部)
- 我在 UITextView 上設置了約束(頂部、前導、尾部、高度)
- 我創建了 UITextView 高度約束的 IBOutlet
- 我在 viewDidLoad() 中的 UITextView 上設置了一個文本(很多會導致滾動的文本)
- 我用下面的代碼設置了 UITextView 的高度約束.在 viewDidLoad() 和 viewDidLayoutSubviews() 中設置文本后,我已經嘗試過了,但沒有成功
self.textViewHeightConstraint.constant = [self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width, FLT_MAX)].height;
UITextView 正在達到它的高度,但 UIScrollView 沒有.有什么我錯過的嗎?
UITextView is getting its height, but UIScrollView isn't. Is there anything I've missed?
推薦答案
經過幾天的研究和接觸 UIScrollView + UITextView + Auto Layout,我成功獲得了一個完整的 UIScrollView.我想分享我的解決方案,以防有人遇到同樣的情況.
After a few days of research and getting my hands dirty with UIScrollView + UITextView + Auto Layout, I successfully got a fully working UIScrollView. I want to share my solution just in case someone might stuck on the same situation.
- 在 Storyboard 的主視圖中添加 UIScrollView
- 在 UIScrollView 中添加 UIView
- 在 UIView 內添加 UITextView(步驟 2 中添加的視圖)
- 確保 UITextView 的啟用滾動"未選中
- 在 UIScrollView 上添加 4 個約束(前導、尾隨、頂部、底部)
- 在 UIView(步驟 2 中添加的視圖)上添加 4 個約束(前導、尾隨、頂部、底部)
- 在 UIView(第 2 步中添加的視圖)和主視圖上添加等寬"約束
- 在 UITextView 上添加 5 個約束(前導、尾隨、頂部、底部、高度).完成此步驟后,您不應收到任何有關約束的錯誤和警告.
- 在 ViewController 上添加 UITextView 高度約束 IBOutlet.
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
并在 Storyboard 中連接 - 以編程方式更改 UITextView 高度約束.
self.textViewHeightConstraint.constant = [self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width, CGFLOAT_MAX)].height;
- Add UIScrollView inside the main view in Storyboard
- Add UIView inside the UIScrollView
- Add UITextView inside the UIView (the view added in step 2)
- Make sure "Scrolling Enabled" of UITextView is unchecked
- Add 4 constraints (leading, trailing, top, bottom) on UIScrollView
- Add 4 constraints (leading, trailing, top, bottom) on UIView (the view added in step 2)
- Add "Width Equally" constraint on UIView (the view added in step 2) and the main view
- Add 5 constraints (leading, trailing, top, bottom, height) on UITextView. After this step you shouldn't get any errors and warnings on constraints.
- Add UITextView height constraint IBOutlet on the ViewController.
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
and connect it in Storyboard - Change the UITextView height constraint programmatically.
self.textViewHeightConstraint.constant = [self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width, CGFLOAT_MAX)].height;
完成所有這 10 個步驟后,您將獲得完整的 UIScrollView 和內部的 UITextView,并且會很開心.
After all of these 10 steps, you'll get fully working UIScrollView with UITextView inside and be happy.
這篇關于帶有自動布局的 UIScrollView 內的 UITextView的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!