[英]How to create slideshow of images within scrollview with autolayout?
[英]Autolayout of the images in scrollView
我以编程方式将图像放入UIScrollview中。 当我在iPhone 8上运行模拟器时,每个图像的宽度完全适合屏幕。 但是,当我在iPhone 8 Plus上运行它时,图像的宽度小于屏幕的宽度。 我认为自动版式有问题。 这背后的可能原因是什么? 我将以下代码放入ViewDidLoad中。
scrollViewData = [scrollViewDataStruct.init(title: nil, image: #imageLiteral(resourceName: "promotion test 1")), scrollViewDataStruct.init(title: nil, image: #imageLiteral(resourceName: "promotion test 2")), scrollViewDataStruct.init(title: nil, image: #imageLiteral(resourceName: "promotion test 3")), scrollViewDataStruct.init(title: nil, image: #imageLiteral(resourceName: "promotion test 4")), scrollViewDataStruct.init(title: nil, image: #imageLiteral(resourceName: "promotion test 5")), scrollViewDataStruct.init(title: nil, image: #imageLiteral(resourceName: "promotion test 6"))]
scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(scrollViewData.count)
var i = 0
for data in scrollViewData {
let view = CustomView(frame: CGRect(x: self.scrollView.frame.width * CGFloat(i), y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height))
view.imageView.image = data.image
self.scrollView.addSubview(view)
i += 1
我将以下代码分开放置
class CustomView: UIView {
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = UIColor.clear
imageView.contentMode = .scaleToFill
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(imageView)
imageView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder){
fatalError("init(coder:) has not been implemented")
}
}
您的scrollview可能在viewDidLoad中具有错误的框架,因为此时尚未触发布局。 尝试将代码移动到viewWillAppear或viewDidLayoutSubviews(并确保其多次调用),或者在设置框架之前添加一个view.layoutIfNeeded()调用。
imageView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
imageView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor , constant: 0).isActive = true
imageView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor , constant: 0).isActive = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.