我以编程方式将图像放入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")
}
}
答案 0 :(得分:0)
您的滚动视图可能在viewDidLoad中具有错误的帧,因为此时尚未触发布局。尝试将代码移动到viewWillAppear或viewDidLayoutSubviews(并确保代码不被多次调用),或者在设置帧之前添加view.layoutIfNeeded()调用。
答案 1 :(得分:0)
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