如何实现点击UIPageControl任意圆点直接跳转对应页面?
UIPageControl点击任意圆点直接跳转的解决办法
别用IBAction里的currentPage获取页码,系统默认会强制每次只跳一页,所以得自己计算点击的目标圆点:
- 在你的点击事件方法里,通过坐标计算目标页码:
@IBAction func pageControlTapped(_ sender: UIPageControl) { let tapX = sender.convert(CGPoint.zero, from: sender).x let singlePageWidth = sender.bounds.width / CGFloat(sender.numberOfPages) let targetPage = Int(floor(tapX / singlePageWidth)) // 直接用targetPage跳转对应的视图控制器 yourPageViewController.setViewControllers([yourVCArray[targetPage]], direction: .forward, animated: true, completion: nil) } - 核心逻辑:把UIPageControl的总宽度平分给每个圆点,用点击位置的X坐标除以单个圆点的宽度,得到的整数就是真正点击的页码,绕开系统的相邻跳转限制。
- 注意事项:如果你的UIPageControl自定义了圆点间距、大小或者有其他样式调整,需要对应修改
singlePageWidth的计算逻辑,确保坐标能匹配正确的页码。
内容的提问来源于stack exchange,提问作者mefahimrahman
相关产品推荐
相关产品推荐

