私はUIScrollViewでカスタムのセグメント化されたコントロールを持つプロジェクトに取り組んでいます。私は、分割されたコントロールを配置するために自動レイアウトを使用したい。私は私のモデルとしてこのプロジェクトを使用しています:https://github.com/honghaoz/UIScrollView-and-AutoLayoutScrollView AutolayoutはLabelで動作しますがカスタムコントロールでは動作しません
import UIKit
class ViewController: UIViewController {
let scrollView = UIScrollView()
var screenBounds: CGRect { return UIScreen.main.bounds }
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup scroll view
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.backgroundColor = UIColor(red:20/255.0, green:119/255.0, blue:61/255.0, alpha:255/255.0)
view.addSubview(scrollView)
// Setup constraints
var views: [String: UIView] = [
"scrollView": scrollView
]
var constraints = [NSLayoutConstraint]()
// External constraints
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: views)
// Internal constraints
// Note: to let scrollView determines its contentSize, four edges should be explicitly specified
let v1 = newLabelWithText("v1 v1 v1 v1 v1 v1 v1 v1 v1 v1")
scrollView.addSubview(v1)
views["v1"] = v1
//Create Segmented Control
let segmentedB = YSSegmentedControl(
//Set Frame in Callback (Required)
frame: CGRect(x: 0, y: 0, width: 400, height: 60),
titles: [
"Yes",
"No"
],
action: {
control, index in
print ("segmented did pressed \(index)")
})
scrollView.addSubview(segmentedB)
views["v4"] = segmentedB
let v2 = newLabelWithText("v2 v2 v2 v2 v2")
views["v2"] = v2
let v3 = newLabelWithText("v3 v3 v3 v3 v3")
views["v3"] = v3
scrollView.addSubview(v3)
// Horizontal, fully specified
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-200-[v4]-300-|", options: .alignAllLastBaseline, metrics: nil, views: views)
// Vertically, fully specified
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-200-[v3]-1000-|", options: .alignAllLeading, metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
print("scrollView.contentSize: \(scrollView.contentSize)")
}
}
何らかの理由で、自動レイアウトは、セグメント化されたコントロールとテキストラベルでうまく動作しますが、ありません。コールバックでは、CGRectのパラメータを入力する必要があるため、幅と高さを設定し、位置パラメータをゼロのままにします。これはスクロールビューがないときに機能しましたが、現在は機能していません。
また、このプロジェクトではストーリーボードを使用していません。すべての制約とビューはプログラムによって作成されます。
ありがとうございました。おかげ