我遇到了显示当前页面的问题。我将 scrollView 与 pageControl 一起使用,我有标签,我在其上显示当前页面和总页数。如果我滚动下一张图片,我的标签会更改 + 1页,但如果我在上一页滚动,我的标签不会在 - 1 上更改,只有在前一页上滚动两次时,我的标签才会更改。
我的代码在这里:
app:passwordToggleEnabled="true" in TextInputLayout
.gif为了更好地理解,请查看图像上方的标签
答案 0 :(得分:1)
Swift 3 +:尝试以下代码行。
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentPage = scrollView.contentOffset.x / scrollView.frame.size.width
self.pageControl.currentPage = Int(currentPage)
}
使用UICollectionView
实现此目的的另一种方法调用这些代理和数据源 UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate 和UICollectionView滚动方向更改为水平
@IBOutlet var collectionViewItem: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var arrayImage = NSArray()
//MARK: ====: CollectionView DataSource :====
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! YourCollectionCell
cell.imageView.image = UIImage(named: arrayImage[indexPath.row] as! String)
return cell
}
//MARK: ====: CollectionView Delegate :====
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.width, height: Your Height)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
//MARK: ====: UIScrollView Delegate :====
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let count = scrollView.contentOffset.x / scrollView.frame.size.width
self.pageControl.currentPage = Int(count)
}
答案 1 :(得分:0)
你已经增加和减少了currentPage
self.pageControl.currentPage += 1
和self.pageControl.currentPage -= 1
你还在做self.numberOfPagesLabel.text = "\(self.pageControl.currentPage + 1)/\(self.imagesArray.count)"
此处self.pageControl.currentPage + 1
错误应该是
self.pageControl.currentPage
完整代码
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentPage = scrollImage.contentOffset.x / UIScreen.main.bounds.size.width
if pageControl.currentPage < imagesArray.count {
self.pageControl.currentPage += 1
self.numberOfPagesLabel.text = "\(self.pageControl.currentPage)/\(self.imagesArray.count)"
} else if pageControl.currentPage != 0 {
self.pageControl.currentPage -= 1
self.numberOfPagesLabel.text = "\(self.pageControl.currentPage)/\(self.imagesArray.count)"
}
pageControl.currentPage = Int(currentPage)
}
希望它对你有所帮助
答案 2 :(得分:0)