2016-06-19 109 views
0

我想讓一個按鈕以編程方式填充scrollview的寬度。我也編程按鈕。 scrollView.width不起作用,我將使用什麼scrollView的寬度?謝謝。如何以編程方式填充scrollview的寬度

class ViewController: UIViewController { 

    @IBOutlet weak var scrollView: UIScrollView! 
    let screenSize: CGRect = UIScreen.mainScreen().bounds 

    let btn1 = UIButton(frame: CGRect(x: 100, y: 100, width:200, height: 50)) 



    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     btn1.backgroundColor = UIColor.clearColor() 
     btn1.layer.cornerRadius = 5 
     btn1.layer.borderWidth = 1 
     btn1.layer.borderColor = UIColor.redColor().CGColor 

     btn1.setTitle("1", forState: .Normal) 


     scrollView.addSubview(btn1) 


    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 
+0

嘗試'scrollView.frame.size.width' –

回答

0

你可以做到這一點

class ViewController: UIViewController { 

    @IBOutlet weak var scrollView: UIScrollView! 
    let screenSize: CGRect = UIScreen.mainScreen().bounds 

    let btn1 = UIButton(frame: CGRect(x: 100, y: 100, width:200, height: 50)) 



    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     btn1.backgroundColor = UIColor.clearColor() 
     btn1.layer.cornerRadius = 5 
     btn1.layer.borderWidth = 1 
     btn1.layer.borderColor = UIColor.redColor().CGColor 

     btn1.setTitle("1", forState: .Normal) 

     scrollView.addSubview(btn1) 

    } 

    // Add this 
    override func viewDidLayoutSubviews() { 
     super.viewDidLayoutSubviews() 

     let newFrame = btn1.frame 
     newFrame.size.width = scrollView.bounds.width 
     btn1.frame = newFrame 
    } 

}

最佳實踐

獲取或設置大小(寬度或高度),使用 「邊界」,而不是 「幀」

要獲得原點(x或y),請使用「框架」

要設置或設置原點(x或y)的動畫,請使用「center」而不是「frame」

即使將縮放或旋轉因子添加到視圖的變換中,center屬性中的值始終有效。對於frame屬性中的值也是如此,如果視圖的變換不等於標識變換,則該屬性被認爲是無效的。

0

兩個選項: -

  1. 您可以通過編程設置自動佈局約束。只需將按鈕的左邊距和右邊距對齊到滾動視圖即可。

  2. viewDidLayoutSubviews方法,你可以設置 btn1.frame.size.width = self.tableview.contentSize.width

相關問題