名字:GLSegmentView
描述:
該控件一般和UIScrollView一起使用,點(diǎn)擊控件通過(guò)代理回調(diào)給UIScrollView來(lái)
改變ContentOffset來(lái)達(dá)到控制頁(yè)數(shù)的效果
功能:
- 可根據(jù)滑動(dòng)的距離來(lái)實(shí)時(shí)更新底部線條的位置和寬度;
- 寬度是根據(jù)每個(gè)分割的控件title的寬度而定;
- 根據(jù)滑動(dòng)距離實(shí)時(shí)顏色漸變;
- 支持code啦扬,xib箩兽,storyboard;
- 支持旋轉(zhuǎn)
展示圖
iPhone

iPad

使用:
xib:
let titles = ["路飛", "Medbanks", "One", "Piece", "god~long"]
self.segmentView.titleArray = titles
self.segmentView.delegate = self
//MARK: UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.segmentView.updateSegmentView(scrollView.contentOffset.x, pageWidth: scrollView.frame.width)
}
//MARK: SegmentSlideViewDelegate
func didSelectSegment(_ index: Int) {
// animated必須為false,如果想點(diǎn)擊segment的時(shí)候也動(dòng)畫(huà)滑動(dòng)粗井,必須添加額外的參數(shù)控制
self.contentScrollView!.setContentOffset(CGPoint(x: CGFloat(index) * ScreenWidth, y: 0), animated: false)
}
code:
// 代碼創(chuàng)建 需要去掉屬性的IBOutlet
self.segmentView = GLSegmentSlideView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 50))
self.segmentView.titleArray = titles
self.segmentView?.delegate = self
self.view.addSubview(self.segmentView!)
如果需要支持旋轉(zhuǎn)
// MARK: 如果是iPhone需要屏幕旋轉(zhuǎn)功能愈犹,必須添加此方法
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.segmentView.beforeLayoutIndex = self.segmentView.currentSelectIndex
}
后記:
在添加支持旋轉(zhuǎn)功能的時(shí)候,遇到了問(wèn)題阻荒,屏幕旋轉(zhuǎn)之后挠锥,有時(shí)scrollView的contentOffset會(huì)發(fā)生改變,這就導(dǎo)致currentIndex(當(dāng)前選中的item)會(huì)發(fā)生變化侨赡。
后來(lái)添加監(jiān)聽(tīng)屏幕旋轉(zhuǎn)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
但是發(fā)現(xiàn)個(gè)坑:
在iPad上旋轉(zhuǎn)屏幕后會(huì)先觸發(fā)此通知(NSNotification.Name.UIDeviceOrientationDidChange
),再調(diào)用layoutSubviews
蓖租。
在iPhone上旋轉(zhuǎn)屏幕后會(huì)先調(diào)用layoutSubviews
,再觸發(fā)此通知(NSNotification.Name.UIDeviceOrientationDidChange
)辆毡。
所以有了在iPhone中如果要支持旋轉(zhuǎn)的話菜秦,必須添加該方法
// MARK: 如果是iPhone需要屏幕旋轉(zhuǎn)功能甜害,必須添加此方法
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.segmentView.beforeLayoutIndex = self.segmentView.currentSelectIndex
}