IOS开发之UIScrollView约束布局
<h2>概要</h2><p>在iOS开发学习中,UIScrollView是绕不过去的一个重要控件。</p>
<p>但是相对于Android的ScrollView,iOS的这个滚动控件的用法简直是复杂一万倍。。。</p>
<p>最主要是目前能找到的大部分的视频教程看到的关于UIScrollView的教程,都是使用Frame布局。没有找到使用AutoLayout布局的教程。。只有看文字教程学习,然后自己总结一下。</p>
<h2>StoryBoard操作布局</h2>
<p>在storyboard中,拖入一个UIScrollView,然后打开右侧的show the size inspector,去掉勾选content layout guides,然后设置UIScrollView的上下左右约束为0,然后重新勾选content layout guides</p>
<p><img src="https://img2020.cnblogs.com/blog/653862/202110/653862-20211002145708770-1668775381.png" width="1360" height="888"></p>
<p>到这里发现Xcode提示约束有错误,原因是是因为UIScrollView的需要有一个ContentView来确定自己的滚动区域。</p>
<p>于是再拖一个UIView到UIScrollView上,然后改名这个UIView为ContentView,鼠标右键拖动这个UIView到UIScrollView的content layout guides上,按住shift勾选前四个约束,让UIScrollView和ContentView四个边建立约束。</p>
<p>然后调整ContentView的约束的constant的值,Xcode默认建立的约束好像不太完美,默认给你自动计算了ContentView的初始大小。</p>
<p><img src="https://img2020.cnblogs.com/blog/653862/202110/653862-20211002150524004-2134075314.png"></p>
<p> </p>
<p>把这个几个调整为0</p>
<p>最后这个几个设置后,发现约束错误的红点依然没有消失。。。点开一看。</p>
<p><img src="https://img2020.cnblogs.com/blog/653862/202110/653862-20211002150707492-1383255680.png"></p>
<p>说明UIScrollView无法根据宽高确定滚动方向。需要设置一下宽高。因为是移动设备。默认应该是Y轴滚动。</p>
<p>那就设置一下宽等于UIScrollView的宽度。高度设为一个高一点的的值,即可滚动</p>
<p>鼠标右键拖动ContentView到Frame Layout Guides上,然后约束ContentView和Frame Layout Guides宽度一样。</p>
<p>然后单独设置ContentView的高度为1000,就发现约束错误的红点没了,运行程序,白色背景出现滚动条,可以上下滑动滚动了。</p>
<p><img src="https://img2020.cnblogs.com/blog/653862/202110/653862-20211002151521244-310087006.png" width="406" height="805"></p>
<h2>使用纯代码布局</h2>
<p>思路和使用StoryBoard一样。只是用代码描述出来而已</p>
<pre class="language-objectivec"><code> let sv = UIScrollView();
sv.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(sv)
sv.backgroundColor = UIColor.systemGray;
sv.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
sv.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
sv.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
sv.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
sv.addSubview(contentView)
contentView.layer.name = "contentView"
contentView.backgroundColor = UIColor.white
contentView.leadingAnchor.constraint(equalTo: sv.contentLayoutGuide.leadingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: sv.contentLayoutGuide.topAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: sv.contentLayoutGuide.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: sv.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: sv.frameLayoutGuide.widthAnchor).isActive = true
contentView.heightAnchor.constraint(equalToConstant: 1000).isActive = true
</code></pre>
<p> </p><br><br>
来源:https://www.cnblogs.com/boxrice/p/15362004.html
頁:
[1]