Swift 4中如何制作与文本共存的常驻自定义垂直滑块?
实现永久显示的自定义ScrollView指示器(Swift 4)
嗨,作为Swift新手能做到这些基础设置已经很棒啦!要实现这个不会消失的自定义滚动指示器,咱们一步步来,操作很简单:
第一步:关闭系统默认指示器
既然要自定义,先把系统自带的指示器关掉,避免冲突。在你的ViewController里找到scrollView的设置代码,加上这两行:
scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false
(如果是水平滚动需求就关水平指示器,垂直需求就关垂直的,按需选择)
第二步:创建自定义指示器视图
咱们用一个普通的UIView来做滑块,你可以自由调整它的颜色、圆角等样式,匹配你想要的效果。比如在viewDidLoad方法里添加这段代码(以垂直指示器为例):
// 计算指示器的基础尺寸 let indicatorWidth: CGFloat = 6 // 滑块高度 = 滚动视图可视高度 × (可视高度 / 内容总高度),保证比例准确 let indicatorHeight = scrollView.bounds.height * (scrollView.bounds.height / scrollView.contentSize.height) // 让指示器靠右,和边缘留8pt间距 let indicatorX = scrollView.bounds.width - indicatorWidth - 8 // 创建指示器视图 let customIndicator = UIView(frame: CGRect(x: indicatorX, y: 0, width: indicatorWidth, height: indicatorHeight)) customIndicator.backgroundColor = UIColor.systemBlue // 换成你想要的颜色 customIndicator.layer.cornerRadius = indicatorWidth / 2 // 圆角让滑块更圆润 customIndicator.tag = 100 // 标记一下,方便后面找到它 scrollView.addSubview(customIndicator)
第三步:监听滚动,同步滑块位置
要让滑块跟着滚动动起来,咱们需要监听scrollView的滚动事件。首先让你的ViewController遵守UIScrollViewDelegate协议:
class YourViewController: UIViewController, UIScrollViewDelegate { // ... 你的其他代码 }
然后在viewDidLoad里设置代理:
scrollView.delegate = self
接着实现滚动监听方法,实时更新滑块位置:
func scrollViewDidScroll(_ scrollView: UIScrollView) { // 找到咱们的自定义指示器 guard let customIndicator = scrollView.viewWithTag(100) else { return } // 计算滚动比例,同步滑块Y轴位置 let scrollRatio = scrollView.contentOffset.y / (scrollView.contentSize.height - scrollView.bounds.height) let maxYOffset = scrollView.bounds.height - customIndicator.bounds.height customIndicator.frame.origin.y = scrollRatio * maxYOffset }
如果是水平滚动需求,把代码里的Y相关参数换成X即可:
// 水平滚动的情况 let scrollRatio = scrollView.contentOffset.x / (scrollView.contentSize.width - scrollView.bounds.width) let maxXOffset = scrollView.bounds.width - customIndicator.bounds.width customIndicator.frame.origin.x = scrollRatio * maxXOffset
第四步:动态更新滑块尺寸(可选)
如果你的textView内容会动态变化(比如用户输入文字),记得在内容改变时重新计算滑块高度,保证比例准确:
// 在textView的内容变化方法里添加 func textViewDidChange(_ textView: UITextView) { scrollView.layoutIfNeeded() // 确保scrollView的contentSize更新完成 guard let customIndicator = scrollView.viewWithTag(100) else { return } // 重新计算指示器高度 let newIndicatorHeight = scrollView.bounds.height * (scrollView.bounds.height / scrollView.contentSize.height) customIndicator.frame.size.height = newIndicatorHeight }
这样你就拥有一个一直显示的自定义滚动指示器啦!你还可以根据需求调整颜色、宽度、位置这些参数,让它完全匹配你想要的样子~
内容的提问来源于stack exchange,提问作者bobcat
相关产品推荐
相关产品推荐

