1
我正在处理UIScrollView中具有自定义分段控件的项目。我想使用自动布局来定位分段控件。我用这个项目作为我的模型:https://github.com/honghaoz/UIScrollView-and-AutoLayoutScrollView Autolayout使用标签但不是自定义控件
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的参数,所以我只需设置宽度和高度并将位置参数保留为零。当没有滚动视图时,这工作,但它现在不工作。
此外,我没有在这个项目中使用故事板。所有约束和视图都以编程方式创建。
任何帮助表示赞赏。由于