2017-07-11 32 views
0

我有一個問題,保持我的程序創建UIButton範圍內的UIView。UIButton以相等的寬度擴展UIView的邊緣swift

該接口構建爲; ScrollView - > ContentView - >(從SQLite循環以編程方式創建的按鈕列表)

這是創建按鈕的代碼;

  let frame = CGRect(x: 0, y: 0 + (numOfButtons * 58), width: Int(ContentView.frame.width) , height: 50) 
      let button = UIButton(frame: frame)     
      button.showsTouchWhenHighlighted=true 
      button.layer.cornerRadius=5 
      button.setTitle(btnTitle, for: []) 
      ContentView.addSubview(button) 
      numOfButtons+=1 
      button.addTarget(self, action: #selector(btnPressed), for: .touchUpInside) 

該代碼給出了這樣的結果;

Picture of button

有沒有人有任何想法,我怎麼能去修復呢?在我看來,ContentView太寬?但我已將它設置爲與ScrollView相等的寬度。

任何和所有的幫助將不勝感激。 在此先感謝

Chris。

+0

要設置按鈕邊框寬度爲ContentView.Width。不,使其寬度與Self.View.Frame.Size.Width相關。內容視圖寬度,你可能有所不同編程方式爲未來的節省時間給與框架相關的按鈕寬度不是內容查看 –

+0

COntentView寬度高度可以變化,但mainFrame寬度高度不是更好設置按鈕框架根據視圖框 –

+0

@iOSGeek我有試過了,它給了我相同的結果。我的ScrollView受限於self.view邊距,並且我希望按鈕的寬度與ScrollView和ContentView的寬度相同(因爲它們的大小相同)。現在即使輸出顯示按鈕寬度和內容視圖寬度相同。它仍然削減右側。 – Chris

回答

0

請檢查我下面的代碼以供參考

這裏是我的代碼輸出

Output

import UIKit 

class ViewController: UIViewController,UIScrollViewDelegate { 


@IBOutlet weak var ContentView: UIView! 

var scrollView: UIScrollView! 
var containerView = UIView() 


override func viewDidLoad() { 
    super.viewDidLoad() 


    let button = UIButton(type: UIButtonType.custom) as UIButton 

    let image = UIImage(named: "image") as UIImage? 
    let frame = CGRect(x: 20, y: 300, width: self.view.frame.size.width - 20 - 20, height: 50) 
    button.frame = frame 
    button.showsTouchWhenHighlighted=true 
    button.layer.cornerRadius=5 
    button.clipsToBounds=true 
    button.setBackgroundImage(image, for: .normal) 
    button.setTitle("Hi", for:.normal) 

    self.scrollView = UIScrollView() 
    self.scrollView.delegate = self 
    self.scrollView.contentSize = CGSize(width: 1000, height: 1000) 


    containerView = UIView() 


    scrollView.addSubview(containerView) 
    view.addSubview(scrollView) 
    self.view.addSubview(button) 


} 

override func viewDidLayoutSubviews() { 
    super.viewDidLayoutSubviews() 

    scrollView.frame = view.bounds 
    containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height) 


}