ScrollView Autolayout使用Label但不使用Custom Control

时间:2017-08-02 11:37:02

标签: ios uiscrollview uicontrol

我正在开发一个在UIScrollView中具有自定义分段控件的项目。我想使用自动布局来定位分段控件。我使用此项目作为我的模型:https://github.com/honghaoz/UIScrollView-and-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的参数,所以我只需设置宽度和高度,并将位置参数保持为零。这在没有滚动视图的情况下有效,但现在不能正常工作。

另外,我在这个项目中没有使用故事板。所有约束和视图都是以编程方式创建的。

任何帮助表示赞赏。感谢

1 个答案:

答案 0 :(得分:1)

我认为你应该在添加约束之前添加这一行

segmentedB.translatesAutoresizingMaskIntoConstraints = false

每当您以编程方式添加约束时,应将此属性设置为false,以使约束对视图生效