我的Xcode项目中的UIScrollView有问题。我正在使用它显示几张图片,但是即使只有一页,它仍会水平滚动。可能与setupPhotosInScrollView()
或scrollViewDidScroll
有关。我不知道如何解决此问题。看来还可以,但仍然出现此错误。请帮忙!
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
// Ad Title
eTitleLabel.text = "\(eObj[EVENTS_TITLE]!)"
// Get photos
let imageFile = eObj[EVENTS_IMAGE1] as? PFFile
imageFile?.getDataInBackground(block: { (data, error) in
if error == nil { if let imageData = data {
self.photosArray.append(UIImage(data: imageData)!)
self.setupPhotosInScrollView()
print("PHOTO 1")
}}})
DispatchQueue.main.async {
if self.eObj[EVENTS_IMAGE2] != nil {
self.pageControl.numberOfPages = 2
let imageFile = self.eObj[EVENTS_IMAGE2] as? PFFile
imageFile?.getDataInBackground(block: { (data, error) in
if error == nil { if let imageData = data {
self.photosArray.append(UIImage(data: imageData)!)
self.setupPhotosInScrollView()
print("PHOTO 2")
}}})
}
// ------------------------------------------------
// MARK: - SETUP PHOTOS IN SCROLLVIEW
// ------------------------------------------------
@objc func setupPhotosInScrollView() {
var X:CGFloat = 0
let Y:CGFloat = 0
let W:CGFloat = view.frame.size.width
let H:CGFloat = view.frame.size.height
let G:CGFloat = 0
var counter = 0
// Loop to create ImageViews
for i in 0..<photosArray.count {
counter = i
// Create a ImageView
let aImg = UIImageView(frame: CGRect(x: X, y: Y, width: W, height: H))
aImg.tag = i
aImg.contentMode = .scaleAspectFit
aImg.image = photosArray[i]
// Add ImageViews based on X
X += W + G
containerScrollView.addSubview(aImg)
} // ./ FOR loop
// Place Buttons into a ScrollView
containerScrollView.contentSize = CGSize(width: W * CGFloat(counter+2), height: H)
}
// ------------------------------------------------
// MARK: - CHANGE PAGE CONTROL PAGES ON SCROLL
// ------------------------------------------------
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = containerScrollView.frame.size.width
let page = Int(floor((containerScrollView.contentOffset.x * 2 + pageWidth) / (pageWidth * 2)))
pageControl.currentPage = page
}
答案 0 :(得分:1)
替换
containerScrollView.contentSize = CGSize(width: W * CGFloat(counter+2), height: H)
使用
containerScrollView.contentSize = CGSize(width: W * CGFloat(photosArray.count), height: H)
当您为contentSize设置的宽度不等于添加的照片数量