直接把我的code貼上來,重點是不要改變scrollView.contentSize,因為auto layout時會自動設定。
----------------------------------------------------------------
//
// BaseScrollViewController.swift
// BaseSettings
//
// Created by HarveyHu on 4/26/16.
// Copyright © 2016 HarveyHu. All rights reserved.
//
import UIKit
import SnapKit
import RxSwift
class BaseScrollViewController: UIViewController {
let contentView = UIView()
let scrollView = UIScrollView()
var originalContentInsets = UIEdgeInsetsZero
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
override func viewDidAppear(animated: Bool) {
super.viewWillAppear(animated)
originalContentInsets = scrollView.contentInset
}
override func setUI() {
super.setUI()
self.scrollView.addSubview(contentView)
self.view.addSubview(scrollView)
}
override func setUIConstraints() {
super.setUIConstraints()
scrollView.snp_makeConstraints { (make) in
make.top.equalTo(self.view)
make.bottom.equalTo(self.view)
make.leading.equalTo(self.view)
make.trailing.equalTo(self.view)
}
contentView.snp_updateConstraints { (make) in
make.top.equalTo(self.scrollView)
make.leading.equalTo(self.scrollView)
make.trailing.equalTo(self.scrollView)
make.bottom.equalTo(self.scrollView)
}
}
// MARK: - Keyboard
@objc override func keyboardWasShown(aNotification: NSNotification)
{
guard let info = aNotification.userInfo, kbSize = info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue().size else {
return
}
let contentInsets = UIEdgeInsetsMake(originalContentInsets.top, originalContentInsets.left, kbSize.height, originalContentInsets.right)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
@objc override func keyboardWillBeHidden(aNotification: NSNotification)
{
let contentInsets = originalContentInsets
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
}
------------------------------------------------------------------
要用的時候就繼承這個VC,把所有內容放到contentView上,但在contentView的constraints設定上要注意寛度可以固定,但高度不要寫死,要跟著內容高度而定。
contentView.snp_updateConstraints { (make) in
make.width.equalTo(self.view)
make.bottom.equalTo(self.theMostBottomView).offset(10)
}