编辑UIScrollView大小后,页面控件停止工作。
您可以看到只有3张幻灯片。但是(1)页面控制无法反映我正在播放的幻灯片,(2)我只能从幻灯片1滚动到幻灯片3。
这是我的代码:
func setupSlideScrollView(slides : [Slide]) {
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 154)
scrollView.contentSize = CGSize(width: 188 * CGFloat(slides.count) + CGFloat((slides.count - 1) * 10), height: 153)
scrollView.isPagingEnabled = true
var lastCellMaxX: CGFloat = 0
let constantSpacingBetweenCell: CGFloat = 10
for i in 0 ..< slides.count {
slides[i].frame = CGRect(x: lastCellMaxX, y: 0, width: 220, height: 153)
scrollView.addSubview(slides[i])
lastCellMaxX += 188 + constantSpacingBetweenCell
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width)
pageControl.currentPage = Int(pageIndex)
}
答案 0 :(得分:1)
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// This will always round down to zero
// since the contentOffset.x will always be smaller than the frame width...
let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width)
// Possible logic to correct this?
let pageIndex = scrollView.contentOffset.x / (width of a slide)
pageControl.currentPage = Int(pageIndex)
}
-由于聊天而更新-
您的滚动视图框架很好。但是,您需要添加一个stackview来容纳所有幻灯片,以便在其中滚动浏览。滚动视图有点棘手,因为您不能只是添加视图并期望它是可滚动的。
这是我用来创建一个包含stackviews的scrollView的测试代码。
func createSlideshow() {
scrollView.translatesAutoresizingMaskIntoConstraints = false
let slide1 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide1.backgroundColor = UIColor.red
let slide2 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide2.backgroundColor = UIColor.blue
let slide3 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide3.backgroundColor = UIColor.yellow
let slides: [UIView] = [slide1, slide2, slide3]
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 10
for slide in slides {
stackView.addArrangedSubview(slide)
slide.widthAnchor.constraint(equalToConstant: slide.frame.width).isActive = true
slide.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true
}
scrollView.addSubview(stackView)
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true
stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
}