-
(iOS) Storyboard없이 오브젝트 넣을때 유용한 메서드(anchor)Programing Language/iOS(Swift) 2019. 10. 29. 18:03728x90반응형
-
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반응형'Programing Language > iOS(Swift)' 카테고리의 다른 글
(iOS) UIImageView에 터치 이벤트 넣기 (0) 2019.10.30 (iOS) CollectionVeiw programmatically 예제 동영상 (0) 2019.10.29 iOS) UITextField 패딩 넣기 (0) 2019.10.29 (iOS) 스토리 보드 없이 ImageView,TextView 구성하기(기초) (0) 2019.10.29 (iOS) 스크롤 뷰란? (0) 2019.10.28 -