class PageContol: UIPageControl {
/// 선택 dot 크기 정의
private var currentSize: CGSize {
return CGSize(width: 17.5, height: 7)
}
/// 기본 dot 크기 정의
private var defaultSize: CGSize {
return CGSize(width: 7, height: 7)
}
/// 기본 dots itemSpace 정의
private var dotSpace: CGFloat {
return 9
}
// Constraint 처리
private var consts = [NSLayoutConstraint]()
private lazy var deactivateConsts = { [unowned self] in
self.subviews.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.deactivate($0.constraints)
}
self.consts.removeAll()
}
private lazy var activateConsts = { [unowned self] in
NSLayoutConstraint.activate(self.consts)
self.consts.removeAll()
}
override var currentPage: Int {
didSet {
// 1. Deactivate constraints.
deactivateConsts()
// 2. 1개 또는 복수 일때의 분기 및 constraints 처리.
switch numberOfPages {
case 1: onePage()
default: severalPage()
}
// 3. Activate constraints.
activateConsts()
}
}
/// Dot가 1개일때의 constraints 처리.
private func onePage() {
guard let dotView = subviews.first else {return}
addSizeConsts(currentSize, to: dotView)
consts.append(dotView.centerXAnchor.constraint(equalTo: centerXAnchor))
consts.append(dotView.centerYAnchor.constraint(equalTo: centerYAnchor))
}
/// Dot가 복수 일때의 constraints 처리.
private func severalPage() {
for (index, dotView) in subviews.enumerated() {
// 1. Vertical 중앙 정렬
consts.append(dotView.centerYAnchor.constraint(equalTo: centerYAnchor))
// 2. 선택 및 기본 dots에 대한 size 처리
if index == currentPage {
addSizeConsts(currentSize, to: dotView)
} else {
addSizeConsts(defaultSize, to: dotView)
}
// 3. Dots간 일정거리 유지 처리
if index == 0 { // 가장 왼쪽
consts.append(dotView.leadingAnchor.constraint(equalTo: leadingAnchor))
} else if index == (subviews.count - 1) { // 가장 오른쪽
consts.append(dotView.leadingAnchor.constraint(equalTo: subviews[index - 1].trailingAnchor,
constant: dotSpace))
consts.append(dotView.trailingAnchor.constraint(equalTo: trailingAnchor))
} else { // 중간
consts.append(dotView.leadingAnchor.constraint(equalTo: subviews[index - 1].trailingAnchor,
constant: dotSpace))
}
}
}
/// 해당 size로 sizeAnchor를 처리한다.
private func addSizeConsts(_ size: CGSize, to view: UIView) {
consts.append(view.widthAnchor.constraint(equalToConstant: size.width))
consts.append(view.heightAnchor.constraint(equalToConstant: size.height))
}
}