Skip to content

Instantly share code, notes, and snippets.

@tifoaudii
Created July 27, 2019 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tifoaudii/1a07fce053f47d2dc647d84bc4fb1fae to your computer and use it in GitHub Desktop.
Save tifoaudii/1a07fce053f47d2dc647d84bc4fb1fae to your computer and use it in GitHub Desktop.
Create custom extension to UIView instance to implement constraint easily
//
// Anchor.swift
// AppStore
//
// Created by Tifo Audi Alif Putra on 27/07/19.
// Copyright © 2019 BCC FILKOM. All rights reserved.
//
import UIKit
extension UIView {
//MARK: - Setup Constraint Easier
func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop:CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight:CGFloat, width: CGFloat, height: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
}
if let bottom = bottom {
self.bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
}
if let right = right {
self.rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
}
if let left = left {
self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
}
if width != 0 {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
if height != 0 {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment