Swift学习笔记(0.1---循环按钮 ScrollView
2017-11-17 本文已影响22人
MMD_
循环按钮+ScrollView处理点击事件
目的:控制器的scroll联动上方按钮的
3EE620DD-1708-4798-857E-B8AC14C3FFEF.png按钮的创建,这个按钮的多少取决与需求,可滑动那就搞个ScrollView,多个联动,不多说直接添代码
fileprivate func setupTitleView() {
var currentHeight: CGFloat = 64
if view.frame.height == iPhoneXHeight {
currentHeight += iPhoneXTopHeight
}
let titleView = UIView(frame: CGRect(x: 0, y: currentHeight, width: view.frame.width, height: 35))
titleView.backgroundColor = UIColor.init(white: 1.0, alpha: 0.7)
view.addSubview(titleView)
for i in 0..<titles.count {
let button = UIButton(type: .custom)
button.tag = 100 + i
button.setTitle(titles[i], for: .normal)
button.setTitleColor(UIColor.darkGray, for: .normal)
button.setTitleColor(UIColor.red, for: .disabled)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.addTarget(self, action: #selector(clickTitleView(_:)), for: .touchUpInside)
let width = titleView.frame.width / CGFloat(titles.count)
let height = titleView.frame.height
button.frame = CGRect(x: CGFloat(i) * width, y: 0, width: width, height: height - 2)
// button.layoutIfNeeded() //不能立即获取button的label的frame 需要强制布局
titleView.addSubview(button)
if i == 0 {
button.titleLabel?.sizeToFit()
self.bottomView.frame = CGRect(x: 0, y: 0, width: button.titleLabel!.frame.width, height: 2)
self.bottomView.center = CGPoint(x: button.center.x, y:button.frame.height + 1)
titleView.addSubview(bottomView)
clickTitleView(button)
}
}
}
@objc fileprivate func clickTitleView(_ sender: UIButton) {
currentButton.isEnabled = true
currentButton = sender
currentButton.isEnabled = false
UIView.animate(withDuration: 0.25) {
self.bottomView.frame = CGRect(x: 0, y: 0, width: self.currentButton.titleLabel!.frame.width, height: 2)
self.bottomView.center = CGPoint(x: self.currentButton.center.x, y:self.currentButton.frame.height + 1)
}
var offSet = contentView.contentOffset
offSet.x = CGFloat(sender.tag - 100) * contentView.frame.width
contentView.setContentOffset(offSet, animated: true)
}
UIScrollViewDelegate
extension ZYDEssenceViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewDidEndScrollingAnimation(scrollView)
let index = scrollView.contentOffset.x / scrollView.frame.width
clickTitleView(view.viewWithTag(100 + Int(index)) as! UIButton)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
let index = scrollView.contentOffset.x / scrollView.frame.width
let vc = childViewControllers[Int(index)]
vc.view.frame = CGRect(x: index * contentView.frame.width, y: 0, width: contentView.frame.width, height: contentView.frame.height)
contentView.addSubview(vc.view)
}
}