func setupScrollView(){
let scrollWidth = scrollView.frame.size.width
let scrollHeight = scrollView.frame.size.height
scrollView.isPagingEnabled = true
var contentWidth : CGFloat = 0.0
for x in 0...bannerImages.count - 1 {
let image = (UIImage(named: bannerImages[x]))
let imageView = UIImageView(image: image)
imageView.clipsToBounds = true
var newX : CGFloat = 0.0
newX = scrollWidth / 2 + scrollWidth * CGFloat(x)
contentWidth += newX
scrollView.addSubview(imageView)
imageView.frame = CGRect(x: newX - itemWidth / 2, y: scrollView.frame.midY - itemWidth / 2, width: itemWidth, height: itemWidth)
}
scrollView.contentSize = CGSize(width:contentWidth, height: scrollHeight)
}
我在viewDidAppear中有这个,我没有自动播放。
我的内容大小宽度增加了不应该存在的大量空间。我有3个图像我正在显示,我可以滚过第3个图像,再次分页2次。
有什么想法吗?
答案 0 :(得分:0)
我不确定你想要完成什么,但我认为你的数学已经完成了。如果您尝试在滚动视图中的x轴上堆叠三个图像并将滚动视图内容大小设置为图像宽度的总和,那么计算您的newX,如newX = itemWidth * CGFloat(x)
也设置图像框架imageView.frame = CGRect(x: newX, y: scrollView.frame.midY - itemWidth / 2, width: itemWidth, height: itemWidth)
。
我认为这不是实施ScrollView
的正确方法!可能不是最佳做法。我认为您应该在child view
中调用ScrollView
contentView
,然后为该视图设置适当的AutoLayout Constraints
。之后,将每个图像添加到contentView
。这样事情会更容易。
查看此博文https://www.natashatherobot.com/ios-autolayout-scrollview/
答案 1 :(得分:0)
我更新此代码检查评论....
func setupScrollView(){
let scrollWidth = scrollView.frame.size.width
let scrollHeight = scrollView.frame.size.height
scrollView.isPagingEnabled = true
var contentWidth : CGFloat = 0.0
for x in 0...bannerImages.count - 1 {
let imageView = UIImageView(image: bannerImages[x])
imageView.clipsToBounds = true
var newX : CGFloat = 0.0
newX = scrollWidth / 2 + scrollWidth * CGFloat(x)
// contentWidth += newX
// This is wrong here. Because you already add scrollview widht in newx and by this line you are adding it again.
contentWidth = newX
scrollView.addSubview(imageView)
imageView.frame = CGRect(x: newX - itemWidth / 2, y: scrollView.frame.midY - itemWidth / 2, width: itemWidth, height: itemWidth)
}
contentWidth = contentWidth + (itemWidth / 2)
// Add this line also beacuse newx store half width so you have to add extra half space in content width
scrollView.contentSize = CGSize(width:contentWidth, height: scrollHeight)
}