LoginSignup
0
1

More than 3 years have passed since last update.

個人的によく使うUIViewExtension

Last updated at Posted at 2019-12-01

他の方が取り上げていたら:bow_tone1:

四隅のアンカー作成

extension UIView {
    func addEdgeConstraint() {
        guard let superview = self.superview else {
            return
        }
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: superview.topAnchor),
            self.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: superview.bottomAnchor),
        ])
    }

    func addEdgeSafeAreaConstraint() {
        guard let superview = self.superview else {
            return
        }
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor),
            self.leadingAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor),
        ])
    }
}

使い方

class ViewController: UIViewController {
    let imageView = UIImageView()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imageView)
        imageView.addEdgeSafeAreaConstraint()
    }
}

インスタンス生成時のプロパティ編集

protocol Layout: UIView {}
extension UIView: Layout {}
extension Layout {
    func layout(_ layout: (Self) -> Void) -> Self {
        layout(self)
        return self
    }
}

使い方

class ViewController: UIViewController {
     let label: UILabel = UILabel()
                            .layout {
                               $0.textColor = .white
                            }
}

もっと上手に書ける方法があったら教えていただけると非常に嬉しいです

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1