How to set subviews with AutoLayout in UIScrollView programmatically?

前端 未结 4 2105
忘掉有多难
忘掉有多难 2020-12-29 10:17

I am creating app with UiScrollview and UIPagectontrol using Autolayout Programmatically, for

I have Created TKScroller as subclass of UIView, I am init it

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 11:08

    I know that the problem has been solved. and i hope that this solution my help for some people so i am posting it.

    Below code is for adding the scrollview to the uiviewcontroller

      self.scrollView = UIScrollView()
        self.scrollView.backgroundColor = UIColor.greenColor()
        self.scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.scrollView.scrollEnabled=true
        self.scrollView.pagingEnabled = true
        self.view.addSubview(self.scrollView)
    
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["scrollView":self.scrollView]))
    
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["scrollView":self.scrollView]))
    

    After added the scrollview and add the subviews/images like this(this is an example for images showing in full size of scrollview like in photos app )

    var prev:UIImgeView?
    
            for var index = 0; index < self.images.count; ++index {
                var iview = UIImgeView()
                iview.setTranslatesAutoresizingMaskIntoConstraints(false)
                self.scrollView.addSubview(iview)
                var image = self.images.objectAtIndex(index) as UIImage
                iview.image = image
                if (index == 0){
                    self.scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[iview(==scrollView)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["iview":iview,"scrollView":self.scrollView]))
                    prev = iview
    
                }
                else{
                    self.scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[prev][iview(==prev)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["iview":iview,"prev":prev!]))
                    prev = iview
                }
                self.scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[iview(==scrollView)]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["iview":iview,"scrollView":self.scrollView]))
    
                if (index == self.images.count-1){
                    self.scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[prev]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["prev":prev!]))
    
                }
    
            }
    

提交回复
热议问题