如何以编程方式填充滚动视图宽度

时间:2016-06-19 14:53:51

标签: ios swift

我正在尝试按钮以编程方式填充scrollview的宽度。我也以编程方式制作了按钮。 scrollView.width不起作用,我将使用什么作为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.
    }


}

2 个答案:

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

}

最佳实践

要获取或设置大小(宽度或高度),请使用" bounds"而不是"框架"

要获得原点(x或y),请使用" frame"

要设置或动画原点(x或y),请使用" center"而不是"框架"

即使已将缩放或旋转因子添加到视图的变换中,center属性中的值也始终有效。对于frame属性中的值也是如此,如果视图的变换不等于身份变换,则该属性被视为无效。

答案 1 :(得分:0)

两个选项: -

  1. 您可以通过编程方式设置 autolayout 约束。只需将按钮的左边距和右边距与滚动视图对齐即可。

  2. viewDidLayoutSubviews 方法中,您可以进行设置 btn1.frame.size.width = self.tableview.contentSize.width