斯威夫特 5+
@IBDesignable class CenteredScrollView: UIScrollView {
@IBInspectable var isVerticallyCentered: Bool = false
@IBInspectable var isHorizontallyCentered: Bool = false
public func center(vertically: Bool, horizontally:Bool, animated: Bool) {
guard vertically || horizontally else {
return
}
var offset = contentOffset
if vertically && contentSize.height <= bounds.height {
offset.y = (contentSize.height / 2) - (bounds.size.height / 2)
}
if horizontally && contentSize.width <= bounds.width {
offset.x = (contentSize.width / 2) - (bounds.size.width / 2)
}
setContentOffset(offset, animated: animated)
}
override func layoutSubviews() {
super.layoutSubviews()
center(vertically: isVerticallyCentered, horizontally: isHorizontallyCentered, animated: false)
}
}