UIScrollView宽度和高度控制

时间:2016-08-11 09:51:54

标签: ios swift uiscrollview

以下是我创建和初始化UIScrollView的方法:

class MyViewController: UIViewController, UIScrollViewDelegate{

    let items = 20, heightPerItem: CGFloat = 40;
    var scrollView: UIScrollView!
    var contentView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        scrollView = UIScrollView(frame: view.bounds)
        contentView = UIView(frame: view.bounds)

        scrollView.backgroundColor = UIColor.blackColor()
        scrollView.autoresizingMask = UIViewAutoresizing.FlexibleHeight

        var yStart: CGFloat = 0 - heightPerItem
        for i in 0 ..< items {
            yStart += heightPerItem
            let label = UILabel(frame: CGRect(x: 0, y: yStart, width: self.view.bounds.size.width, height: heightPerItem - 1))
            label.text = "\(i) testing..."
            label.backgroundColor = UIColor.brownColor()
            scrollView.addSubview(label)
        }

        view.addSubview(scrollView)
    }

    override func viewDidLayoutSubviews() {
        scrollView.addSubview(contentView)
        scrollView.contentSize.height = heightPerItem * CGFloat(items)
    }
}

这是输出:

enter image description here

如果我从未尝试过方向改变,那就没关系了:

enter image description here

所以,请看以下两点:

  1. scrollView是否还有其他任何方法可以自动获得身高(至少我不想做scrollView.contentSize.height = heightPerItem * CGFloat(items))?
  2. 如何重新编写代码,以便scrollView的宽度随着方向的改变而改变?

1 个答案:

答案 0 :(得分:0)

我对您的代码做了一些小改动并放置了

scrollView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, .FlexibleWidth]

let label = UILabel(frame: CGRect(x: 0, y: yStart, width: self.view.bounds.size.height, height: heightPerItem - 1))

它解决了横向宽度的问题。

如果要在方向更改时控制大小更改,可以覆盖func viewWillTransitionToSize,例如:

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    if UIDevice.currentDevice().orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }


}

此外,对于第1部分.AFAIK,UIScrollView没有最多需要y坐标的属性,但我们可以制作一个像这样的小代码:

    func rectMax() -> CGRect {
       var cR = CGRectZero
       for sv in scrollView.subviews {
           cR = CGRectUnion(cR, sv.frame)
       }

    return cR
}

并且你可以使用:

        scrollView.contentSize = rectMax().size