2017-08-02 64 views
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的參數,所以我只需設置寬度和高度並將位置參數保留爲零。當沒有滾動視圖時,這工作,但它現在不工作。

此外,我沒有在這個項目中使用故事板。所有約束和視圖都以編程方式創建。

任何幫助表示讚賞。由於

回答

0

我想你應該添加約束

segmentedB.translatesAutoresizingMaskIntoConstraints = false 

無論何時添加約束編程,你應該將此屬性設置爲false,以便限制採取對視圖效果之前加入這行

相關問題