ios - UIPageControl 中的控制 "active"点

标签 ios swift uipageviewcontroller uipagecontrol

我的设计师要求我在 UIPageViewController 中为 10 个 View 显示 3 个点。

当前 3 个 View Controller 显示时,第 0 个点应突出显示;当接下来的 4 个 View Controller 显示时,第一个点应该突出显示;当最后 3 个 View Controller 显示时,第二个点应突出显示。

到目前为止,我能够在 UIPageControl 中显示 3 个点,但指示点只是旋转,指示 n%3 位置处于事件状态。

func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
    return 3
}

我还没有看到任何关于如何使用 UIPageControl 控制索引是事件索引的文档,所以我不确定这是否是 Apple 希望您能够覆盖的内容。

如果有办法完成我想做的事情,我将不胜感激。

最佳答案

事实证明,我想要完成的事情不能用 UIPageViewController 来完成。默认情况下,此类中的 UIPageControl 无法直接重写。

相反,我能够使用 UICollectionView(通过一种技巧,使其在页面更改效果中类似于 UIPageViewController)和 UIPageControl 的组合,作为同一总体 UIViewController 的 subview 。

class MyPageViewController : UIViewController {
    // MARK: subviews
    private var collectionView:UICollectionView!
    /// the collection layout controls the scrolling behavior of the collection view
    private var collectionLayout = MyLayout()
    private var pageControl = UIPageControl()

    let CollectionViewCellReuseIdentifer = "CollectionViewCellReuseIdentifier"

    // MARK: autolayout
    private var autolayoutConstraints:[NSLayoutConstraint] = [NSLayoutConstraint]()



    // MARK: constructors
    init() {
        super.init(nibName: nil, bundle: nil)
    }



    // MARK: UIViewController lifecycle methods
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupView()
    }



    /**
    Set up the collection view, page control, skip & log in buttons
    */
    func setupView() {
        self.setupCollectionView()
        self.setupPageControl()

        self.setupConstraints()

        self.view.addConstraints(self.autolayoutConstraints)
    }

    /**
    Set up the collection view
    */
    func setupCollectionView() {
        self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.collectionLayout)
        self.collectionView.translatesAutoresizingMaskIntoConstraints = false
        self.collectionView.registerClass(MyPageView.self, forCellWithReuseIdentifier: self.CollectionViewCellReuseIdentifer)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.backgroundColor = UIColor.whiteColor()
        self.collectionView.scrollEnabled = true
        self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;


        self.collectionLayout.minimumInteritemSpacing = 1
        self.collectionLayout.minimumLineSpacing = 1
        self.collectionLayout.scrollDirection = .Horizontal
        self.collectionLayout.delegate = self

        self.view.addSubview(self.collectionView)
    }

    /**
    Set up view showing pagination dots for slideshow items
    */
    func setupPageControl() {
        self.pageControl.translatesAutoresizingMaskIntoConstraints = false
        self.pageControl.numberOfPages = 3
        self.pageControl.backgroundColor = UIColor.whiteColor()

        self.view.addSubview(self.pageControl)
    }

    func setupConstraints() {
        let views:[String:AnyObject] = [
            "collectionView" : self.collectionView,
            "pageControl" : self.pageControl,
        ]

        self.autolayoutConstraints.appendContentsOf(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "V:|[collectionView][pageControl]|",
                options: .AlignAllCenterX,
                metrics: nil,
                views: views
            )
        )

        self.autolayoutConstraints.appendContentsOf(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "H:|[collectionView]|",
                options: .AlignAllCenterY,
                metrics: nil,
                views: views
            )
        )

        self.autolayoutConstraints.appendContentsOf(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "H:|[pageControl]|",
                options: NSLayoutFormatOptions(),
                metrics: nil,
                views: views
            )
        )
    }
}

extension MyPageViewController : MyPageViewControllerDelegate {
    func didSwitchToPage(imageIndex: Int) {
        if imageIndex < 3 {
            self.pageControl.currentPage = 0
        } else if imageIndex < 7 {
            self.pageControl.currentPage = 1
        } else {
            self.pageControl.currentPage = 2
        }

        self.pageControl.setNeedsDisplay()
    }
}

布局类源 self 的同事在研究类似问题时发现的答案。 http://karmadust.com/centered-paging-with-preview-cells-on-uicollectionview/

/**
*  Delegate for slide interactions
*/
protocol MyPageViewControllerDelegate {
    /**
    Triggered when a new page has been 'snapped' into place

    - parameter imageIndex: index of the image that has been snapped to
    */
    func didSwitchToPage(imageIndex: Int)

}

class MyLayout : UICollectionViewFlowLayout {
    var delegate:MyPageViewControllerDelegate?

    /*
    Allows different items in the collection to 'snap' onto the current screen section.
    Based off of http://karmadust.com/centered-paging-with-preview-cells-on-uicollectionview/
    */
    override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {

        if let cv = self.collectionView {

            let cvBounds = cv.bounds
            let halfWidth = cvBounds.size.width * 0.5;
            let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth;

            if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds) {

                var candidateAttributes : UICollectionViewLayoutAttributes?
                // the index of the image selected
                var index:Int = 0

                for attributes in attributesForVisibleCells {

                    // == Skip comparison with non-cell items (headers and footers) == //
                    if attributes.representedElementCategory != UICollectionElementCategory.Cell {
                        index++
                        continue
                    }

                    if let candAttrs = candidateAttributes {

                        let a = attributes.center.x - proposedContentOffsetCenterX
                        let b = candAttrs.center.x - proposedContentOffsetCenterX

                        if fabsf(Float(a)) < fabsf(Float(b)) {
                            candidateAttributes = attributes;
                        }

                    }
                    else { // == First time in the loop == //

                        candidateAttributes = attributes;
                        index++
                        continue;
                    }

                }

                // Beautification step , I don't know why it works!
                if(proposedContentOffset.x == -(cv.contentInset.left)) {
                    return proposedContentOffset
                }

                if let delegate = self.delegate {
                    delegate.didSwitchToPage((candidateAttributes?.indexPath.row)!)
                }

                return CGPoint(x: floor(candidateAttributes!.center.x - halfWidth), y: proposedContentOffset.y)

            }


        }

        // fallback
        return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
    }
}

注意:我删减了我使用的实际代码并替换了一堆名称,以使它们更适合示例。我没有运行这个特定的代码,也没有在我的 IDE 中测试错误。话虽这么说,代码背后的方法是可靠的。

关于ios - UIPageControl 中的控制 "active"点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33247245/

相关文章:

ios - iOS swift 中的集成

ios - 如何在 Ios 中使用 SDWebImage 在 PageViewController 中加载 url 图片

ios - 一个模型应该做多少设置?

swift - 无法在 Xcode 10 中使用源代码编辑器扩展

iOS:如何使 swift 3 中事件中的每个计时器失效或终止?

ios - 检查播放器是否在另一个节点之上?

ios - 基于页面的应用程序和手势识别器

iOS Swift GestureRecognizer 不工作

ios - 使用 swift 3 在 Firebase 数据库上进行简单搜索

ios - 有没有办法解决ios中的内存崩溃问题