gpt4 book ai didi

swift - UIScrollView 显示 subview 不正确

转载 作者:行者123 更新时间:2023-11-30 11:38:29 26 4
gpt4 key购买 nike

我试图在 ScrollView 中显示简单的自定义 View 。这是我的代码:

struct scrollViewDataStruct {
let title: String?
let image: UIImage?
}

class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!

var scrollViewData = [scrollViewDataStruct]()

override func viewDidLoad() {
super.viewDidLoad()
scrollViewData = [
scrollViewDataStruct(title: "First", image: #imageLiteral(resourceName: "iPhone 8 Copy 2")),
scrollViewDataStruct(title: "Second", image: #imageLiteral(resourceName: "iPhone 8 Copy 3"))
]
self.scrollView.backgroundColor = .yellow
scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(scrollViewData.count)
var i = 0
for _ in scrollViewData {
let view = CustomView(frame: CGRect(x: self.scrollView.frame.width * CGFloat(i), y: 0, width: scrollView.frame.width, height: self.scrollView.frame.height))
self.scrollView.addSubview(view)
i += 1
}
// Do any additional setup after loading the view, typically from a nib.
}

}

class CustomView: UIView {

let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = UIColor.blue
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")
}
}

如您所见,CustomView 的框架=scrollView 的框架,但是当我运行应用程序时,它并不像我预期的那样:

然后,在 Storyboard中,我将设备从 iphone8 更改为 iphone 8 plus 并再次运行。它正确显示 CustomView 。我不知道, scrollView 总是正确的,但 CustomView 不是。有什么建议吗?

最佳答案

您的问题是,在自动布局运行并确定 ScrollView 的frame的大小之前,您正在访问scrollView的frame实际设备。快速解决方法是将您的设置代码移至 viewDidLayoutSubviews 的重写中。但您必须小心,因为与 viewDidLoad 不同,viewDidLayoutSubviews 将运行多次,因此您必须确保不会多次添加 View 。

// property - have we set up the views yet?
var setup = false

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !setup {
scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(scrollViewData.count)
var i = 0
for _ in scrollViewData {
let view = CustomView(frame: CGRect(x: self.scrollView.frame.width * CGFloat(i), y: 0, width: scrollView.frame.width, height: self.scrollView.frame.height))
self.scrollView.addSubview(view)
i += 1
}
setup = true
}
}

您应该考虑使用约束将 View 放置在scrollView内容中,而不是扰乱frame计算,然后自动布局会自动做正确的事情。

关于swift - UIScrollView 显示 subview 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49474011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com