Slide View 側滑多頁面
本專案適用於少量頁面切換
加入協定
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
宣告資料
var sv = UIScrollView()
var btn = UIButton()
var line = UIView()
var tv1 = UITableView()
var tv2 = UITableView()
var data = Array(1...10)
let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height
viewDidLoad
背景顏色
view.backgroundColor = .lightGray
UILabel
for i in 0...1 { let I = CGFloat(i) btn = UIButton(frame: CGRect(x: 0, y: 0, width: WIDTH / 2, height: 44)) btn.center = CGPoint(x: (1 + 2 * I) * WIDTH / 4, y: 42) btn.setTitle("btn \(Int(I + 1))", for: .normal) btn.backgroundColor = .blue btn.tag = Int(I + 1) btn.addTarget(self, action: #selector(btnpressed), for: .touchDown) view.addSubview(btn) }
UIView
line.frame = CGRect(x: WIDTH / 8, y: 56, width: WIDTH / 4, height: 3) line.backgroundColor = .white line.layer.cornerRadius = 1.5 view.addSubview(line)
UIScrollView
sv.frame = CGRect(x: 0, y: 64, width: WIDTH, height: HEIGHT) sv.contentSize = CGSize(width: WIDTH * 2, height: 0) sv.delegate = self sv.backgroundColor = .black sv.isPagingEnabled = true view.addSubview(sv)
UITableView
tv1 = UITableView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: HEIGHT - 64), style: .plain) tv1.delegate = self tv1.dataSource = self tv1.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tv1.backgroundColor = .lightGray tv1.tableFooterView = UIView(frame: .zero) sv.addSubview(tv1) tv2 = UITableView(frame: CGRect(x: WIDTH, y: 0, width: WIDTH, height: HEIGHT - 64), style: .plain) tv2.delegate = self tv2.dataSource = self tv2.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tv2.backgroundColor = .lightGray tv2.tableFooterView = UIView(frame: .zero) sv.addSubview(tv2)
滑動觸發動作
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
line.frame.origin.x = WIDTH / 8 + offset / 2
}
按鈕點選動作
func btnpressed(sender: UIButton) {
switch sender.tag {
case 1 :
viewslide(0)
case 2:
viewslide(WIDTH)
default:
break
}
}
滑動動作
func viewslide(_ distance: CGFloat, completion: ((Bool) -> Void)! = nil) {
UIView.animate(withDuration: 0.3,
delay: 0,
options: [.curveEaseInOut],
animations: { () -> Void in
self.line.frame.origin.x = self.WIDTH / 8 + distance / 2
self.sv.contentOffset.x = distance
},
completion: nil)
}
UITableViewDelegate、UITableViewDatasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let DATA: Bool = tableView == tv1
return DATA ? data.count : data.count - 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let DATA: Bool = tableView == tv1
let name = data[indexPath.row]
cell?.textLabel?.text = DATA ? "頁面一 \(name)" : "頁面二 \(name)"
cell?.textLabel?.textColor = DATA ? .black : .white
cell?.backgroundColor = DATA ? .white : .red
return cell!
}
下載完整範例 OneDrive