Autolayout으로 아이의 크기에 맞게 신축할 수 있는 상자를 만들고 싶어요.

5857 단어 iOS
AutoLayout으로 신축성 있는 포석을 만들 때 좀 곤란해서 적어놨어요.

하고 싶은 거.

  • 높이를 동적으로 변경할 수 있음
  • 의 내용을 유지하고 싶은 Aspect비
  • 원래 크기 1:1
    신축1:2
    신축1:3



    방법


    외부 뷰에 적절한 제한
  • Center in Horizontal
  • Center in Vertical
  • Propoortional With to SuperView2(window 대비 절반)
  • Height>=150(최소 높이를 적당히 결정한다. 높지 않을 수도 있다)
  • 여기서는 높이를 결정할 수 없고 오류가 발생할 수 있지만 잠시 놓아두다
    이어서 아이뷰의 제약이 더해졌다.

    4주간의 Mergin을 0으로 확장하고 Apsect 비율을 낮은 우선 순위로 설정합니다.
  • Trailling Space To: Superview
  • Leading Space To: Superview
  • Bottom Space To: Superview
  • Top Space To: Superview
  • 1:1 Ratio to: Superview (priority 500)
  • 서브뷰의 Aspect 비율을 전환하는 코드를 동적으로 입력합니다.
    class ViewController: UIViewController {
        @IBOutlet weak var innerContentView: UIView!
        private var touched: Bool = false
        private var constraint = NSLayoutConstraint()
    
        @IBAction func buttonDidTouchUped(sender: AnyObject) {
            touched = !touched
            let ratio = touched ? CGFloat(2.0) : CGFloat(3.0)
            updateConstraint(ratio)
        }
    
        func updateConstraint(ratio: CGFloat) {
            innerContentView.removeConstraint(constraint)
            constraint = NSLayoutConstraint(
                item: innerContentView,
                attribute: NSLayoutAttribute.Height,
                relatedBy: NSLayoutRelation.Equal,
                toItem: innerContentView,
                attribute: NSLayoutAttribute.Width,
                multiplier: ratio,
                constant: CGFloat(0.0)
            )
            constraint.priority = 501
            innerContentView.addConstraints([ constraint ])
            innerContentView.updateConstraints()
        }
    }
    
    여기에 초기치가 설정한 priority보다 높은 priority를 추가하고updateConstraints()는 서브뷰의 크기를 동태적으로 반영하며 이에 따라 부모의 뷰의 높이가 신축된다.

    코드

  • https://github.com/mattak/ElasticDialogSample
  • 좋은 웹페이지 즐겨찾기