IBInspectable プロパティを使用して単純な UIScrollView 拡張機能を作成し、コンテンツを水平または垂直方向に中央揃えにしました。スクロールビューのコンテンツサイズがスクロールビューのサイズよりも小さい場合にのみ機能します。
Swift 5.2 コードは次のとおりです。
import UIKit
@IBDesignable class CenteredScrollView: UIScrollView {
@IBInspectable var verticallyCentered: Bool = false
@IBInspectable var horizontallyCentered: Bool = false
override var contentSize: CGSize {
didSet {
if contentSize.height <= bounds.height && verticallyCentered {
centerVertically()
}
if contentSize.width <= bounds.width && horizontallyCentered {
centerHorizontally()
}
}
}
private func centerVertically() {
let yContentOffset = (contentSize.height / 2) - (bounds.size.height / 2)
contentOffset = CGPoint(x: contentOffset.x, y: yContentOffset)
}
private func centerHorizontally() {
let xContentOffset = (contentSize.width / 2) - (bounds.size.width / 2)
contentOffset = CGPoint(x: xContentOffset, y: contentOffset.y)
}
}