@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var btnBack: UIButton!
@IBOutlet weak var btnForward: UIButton!
let headerView = UIView()
headerView.backgroundColor = UIColor.white
for i in 0..<selectedRestaurant.multipleImages.count {
let url = selectedRestaurant.multipleImages[i]
let imgView = UIImageView()
imgView.frame = CGRect(x: CGFloat(i) * self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: scrollView.frame.size.height)
let task = URLSession.shared.dataTask(with: URL(string: url as! String)!, completionHandler: { (data, response, error) in
if error == nil {
if data != nil {
imgView.contentMode = UIViewContentMode.scaleAspectFill
imgView.image = UIImage(data: data!)
}
}
})
scrollView.addSubview(imgView)
scrollView.contentSize = CGSize(width: self.view.frame.size.width * CGFloat(selectedRestaurant.multipleImages.count), height: scrollView.frame.size.height)
寫代碼回點擊< < < <
let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) - 1
print("\(index)")
if index >= 0 {
scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
}
寫代碼BTN接下來點擊>>>>>
let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) + 1
print("\(index)")
if index < (selectedRestaurant.multipleImages.count) {
scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
}
你必須設置了滾動的內容視圖的等於最後寬按鍵x軸+最後一個按鈕的寬度 –
您需要添加的UIView內滾動視圖將作爲滾動視圖的內容查看,因爲你需要水平滾動,因此contentView的寬度應該大於scrollview的框架,因此請添加與scrollview的高度相同的高度約束,並將寬度設置爲較大的值,例如2000.現在,創建一個寬度約束的IBOutlet,您將調整它根據你的內容,在設置containerView之後,在contentView上添加所有按鈕而不是滾動視圖..並根據最後添加的按鈕計算containerView的寬度,並且你的滾動視圖應該可以工作。 – iphonic
Humm,我認爲你搞亂了滾動視圖的可滾動內容的內容大小。您必須設置滾動視圖的內容視圖(您已將視圖放置爲超級按鈕視圖),確保該視圖的寬度約束符合您的要求,即等於所有按鈕的總和寬度+所有間距之和按鈕,你可以發佈你的項目git鏈接,以便我可以爲你解決。 – dip