ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • (iOS) Storyboard없이 오브젝트 넣을때 유용한 메서드(anchor)
    Programing Language/iOS(Swift) 2019. 10. 29. 18:03
    728x90
    반응형
    • descriptionTextView.topAnchor.constraint 와 같이 top,bottom,leading,triling등을 다 코드로 상속 시켜줘야하는데 anchor메서드를 사용하면 descriptionTextView.anchor(top : ,right : ,...) 으로 간편하게 할 수 있다.

    extension UIView {
        
        func anchor(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, paddingTop: CGFloat? = 0,
                    paddingLeft: CGFloat? = 0, paddingBottom: CGFloat? = 0, paddingRight: CGFloat? = 0, width: CGFloat? = nil, height: CGFloat? = nil) {
            
            translatesAutoresizingMaskIntoConstraints = false
            
            if let top = top {
                topAnchor.constraint(equalTo: top, constant: paddingTop!).isActive = true
            }
            
            if let left = left {
                leftAnchor.constraint(equalTo: left, constant: paddingLeft!).isActive = true
            }
            
            if let bottom = bottom {
                if let paddingBottom = paddingBottom {
                    bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
                }
            }
            
            if let right = right {
                if let paddingRight = paddingRight {
                    rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
                }
            }
            
            if let width = width {
                widthAnchor.constraint(equalToConstant: width).isActive = true
            }
            
            if let height = height {
                heightAnchor.constraint(equalToConstant: height).isActive = true
            }
        }
    }
    
    //사용 예시
    
    followButton.anchor(top: topAnchor, right: rightAnchor,
                                 paddingTop: 64, paddingRight: 32, width: 32, height: 32)
                                 
    //이 메서드가 없었더라면?
    descriptionTextView.topAnchor.constraint(equalTo: bearImageView.bottomAnchor, constant: 50).isActive = true
            descriptionTextView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
            descriptionTextView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
            descriptionTextView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 300).isActive = true
    
    
    // 4번 적을거를 한번만 적어주면된다.
    728x90
    반응형
Designed by Tistory.