iOS 응용 (swift)
[iOS - swift] scroll view에서 원하는 위치로 scroll하기
jake-kim
2020. 10. 17. 22:20
sc특정 textField를 탭한 경우, 특정 위치로 scroll시키는 로직

ScrollView만들기
여기 참고
방향 정의
public enum ScrollDirection {
case top
case center
case bottom
}
extension으로 scroll이동 구현
public extension UIScrollView {
func scroll(to direction: ScrollDirection) {
DispatchQueue.main.async {
switch direction {
case .top:
self.scrollToTop()
case .center:
self.scrollToCenter()
case .bottom:
self.scrollToBottom()
}
}
}
private func scrollToTop() {
setContentOffset(.zero, animated: true)
}
private func scrollToCenter() {
let centerOffset = CGPoint(x: 0, y: (contentSize.height - bounds.size.height) / 2)
setContentOffset(centerOffset, animated: true)
}
private func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
if(bottomOffset.y > 0) {
setContentOffset(bottomOffset, animated: true)
}
}
}
각 텍스트 필드 델리게이트 설정
tfTop.delegate = self
tfCenter.delegate = self
tfBottom.delegate = self
텍스트 필드에 becomeFirstResponder가 되는경우 작동하는 델이게이트인, textFieldDidBeginEditing(_:)함수에 분기
extension ViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
switch textField {
case tfTop:
scrollView.scroll(to: .top)
case tfCenter:
scrollView.scroll(to: .center)
case tfBottom:
scrollView.scroll(to: .bottom)
default:
break
}
}
}