TableViewをスクロールして、あるセクションが表示されている時だけNavigationbarの下にViewを表示する
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if self.tableView.indexPathsForVisibleRows?.first?.section == ClinicInfomationSection.services.rawValue {
if !extensionView.isExpanded && !extensionView.isMoving {
extensionView.expand()
}
let firstVisibleCell = self.tableView.visibleCells.first
if let cell = firstVisibleCell as? ClinicServiceCell {
extensionView.setLabelText(cell.serviceTitle.text!)
}
} else {
if extensionView.isExpanded && !extensionView.isMoving {
extensionView.contract()
}
}
}
class ExtensionView: UIView {
@IBOutlet weak var label: UILabel?
var isExpanded: Bool = false
var isMoving: Bool = false
func expand() {
isMoving = true
self.isHidden = false
self.alpha = 0
self.y -= self.height
UIView.animate(withDuration: 0.2,
animations: { () -> Void in
self.y += self.height
self.alpha = 1
},
completion: { (Bool) -> Void in
self.isExpanded = true
self.isMoving = false
})
}
func contract() {
isMoving = true
UIView.animate(withDuration: 0.2,
animations: { () -> Void in
self.y -= self.height
self.alpha = 0
},
completion: { (Bool) -> Void in
self.isHidden = true
self.y += self.height
self.isExpanded = false
self.isMoving = false
})
}
func setLabelText(_ text: String, fromTop: Bool = true) {
CATransaction.begin()
let animation = CATransition()
animation.duration = 0.2
animation.type = kCATransitionPush
animation.subtype = fromTop ? kCATransitionFromTop : kCATransitionFromBottom
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
isMoving = true
CATransaction.setCompletionBlock {
self.isMoving = false
}
self.label?.layer.add(animation, forKey: "changeLabelText")
self.label?.text = text
CATransaction.commit()
}
}