![](/img/trans.png)
[英]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.