ios - 如何将内容宽度设置为设备/父宽度的大小?
问题描述
我的功能滚动中的图像奇怪地出现在较小尺寸的手机中,例如iPhone 5s
、iPhone 6
等。
编辑:我UIScrollView
用来做这个。:)
我尝试将我的代码添加到viewDidLayoutSubviews
其中,viewWillLayoutSubviews
但它似乎不起作用。
//第一次尝试
override func viewDidLayoutSubviews() {
featureScroll.contentSize = CGSize(width: self.view.bounds.width * CGFloat(featureArray.count), height: 300)
}
//第二次尝试
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()()
featureScroll.contentSize = CGSize(width: self.view.bounds.width * CGFloat(featureArray.count), height: 300)
}
编辑://我如何将图像加载到 featureScroll
let feature1 = ["image": "ic_home1"]
let feature2 = ["image": "ic_home2"]
let feature3 = ["image": "ic_home3"]
var featureArray = [Dictionary<String, String>](
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
featureArray = [feature1, feature2, feature3]
featureScroll.isPagingEnabled = true
featureScroll.contentSize = CGSize(width: self.view.bounds.width * CGFloat(featureArray.count), height: 300)
featureScroll.showsHorizontalScrollIndicator = false
featureScroll.delegate = self
loadFeatures()
}
func loadFeatures(){
for (index, feature) in featureArray.enumerated() {
if let featureView = Bundle.main.loadNibNamed("Feature", owner: self, options: nil)?.first as? FeatureView {
featureView.featureImage.image = UIImage(named: feature["image"]!)
featureScroll.addSubview(featureView)
featureView.frame.size.width = featureScroll.bounds.size.width
featureView.frame.origin.x = CGFloat(index) * featureScroll.bounds.size.width
}
}
}
func scrollViewDidScroll(_ featureScroll: UIScrollView) {
let page = featureScroll.contentOffset.x / featureScroll.frame.size.width
featurePageControl.currentPage = Int(page)
}
下面的链接显示了实际结果,我想摆脱空白,我应该怎么做?
--> https://imgur.com/8AUZh4U.png
预先感谢您的帮助!:)
解决方案
理论
scrollView 需要知道它的位置(它的 frame = 位置和大小)和它的内容的大小(它将滚动)。
一个垂直的 stackView 需要知道它的位置 (x, y) 和它的宽度。它的高度由它的内容和设置(例如项目之间的间距)决定。
例子
因此,根据您的需要,在整个屏幕上有一个 scrollView 并在里面有一堆垂直视图,您可以做这样的事情(只有约束,没有以编程方式设置):
UIScrollView:
0 到其父视图的顶部、前导、尾随、底部约束
垂直 UIStackView:
ViewController 视图的前导、尾随、约束为 0。Top,leading, trailing,bottom = 0 to its superview (scrollView) > 这将使 ScrollView ...当 stackView 内容大于 scrollView 的高度时滚动
StackView 的项目:
在你的情况下,我认为这是一堆 imageViews。每个项目都需要设置自己的高度。
ImageView 高度的总和(以及在 stackView 中设置的间距)将确定 stackView 的高度,这将确定 scrollView 的内容高度(以及可滚动高度)。
有关 UIScrollView 的更多信息,请参阅此处的文档
有关 UIStackView 的更多信息,请参阅此处的文档
推荐阅读
- oracle - 如何在 oracle 中连接定义的变量?
- javascript - 如何过滤到仅查看所需属性的对象(js)
- python - 如何从views.py函数收集变化的变量到模板而不在django中重新加载
- powershell - 如何在不使用变量的情况下在 AD 对象的属性上应用带有子字符串的拟合器?
- python - Sqlalchemy - 创建 Amazon S3 预签名 URL
- julia - 我的 Julia 循环/去矢量化代码出了什么问题
- excel - 我需要什么功能才能获得比上一年增加的年初至今百分比?
- python - 如何实现一个类?
- python - 如何将 JSON 对象键写入 CSV 文件?
- java - KakaConsumer.poll(timeoutMs) 和 KafkaConsumer.poll(Duration.ZERO) 的区别