UIButton以相同的宽度快速延伸到UIView的边缘

时间:2017-07-11 03:29:16

标签: ios swift uibutton

我在将程序创建的UIButton保存在UIView的范围内时遇到了一些问题。

界面构建如下; 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的等宽。

非常感谢任何和所有帮助。 提前致谢

克里斯。

1 个答案:

答案 0 :(得分: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)


}