autolayoutをコードで実装する入門 – Swift4

説明

autolayoutをコードで実装してみたいと思います。制約を考えるときのポイントは、どのオブジェクトを基準に、対象のオブジェクトに制約を与えるかです。相対的な位置関係を指定します。難しい、言葉で説明するの。ていうか、面倒くせえ笑(<-サイテー)でも、アインシュタインも言っていた。小学生、おばあちゃんが分かるように説明できなければ理解したとは言えない。

実装

//
//  ViewController.swift
//  test
//
//  Created by ryosuke-hujisawa on 2017/11/25.
//  Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()



        /*

         UIViewを作る。ここはオートレイアウトを使わずに
         self.viewの大きさを基準に描画位置を決める


         */
        let BlueView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
        let bgColor = UIColor.blue
        BlueView.center = CGPoint(x:self.view.frame.width/2,y:self.view.frame.height/2)
        BlueView.backgroundColor = bgColor
        self.view.addSubview(BlueView)


        /*


         UILabelを作る。これはオートレイアウトによる描画方法を採用する


         */
        let myLabel:UILabel = UILabel()
        myLabel.backgroundColor = UIColor.blue
        myLabel.textAlignment = NSTextAlignment.center
        myLabel.backgroundColor = UIColor.red // 赤
        myLabel.text = "テキスト"
        myLabel.numberOfLines=1
        myLabel.textColor=UIColor.black
        myLabel.font=UIFont.systemFont(ofSize: 22)
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myLabel)


        /*


         ここからオートレイアウトをコードで実行する

         */

        // myLabelのleadingAnchor(左端)はBlueViewのleadingAnchor(左端)と同じ
        myLabel.leadingAnchor.constraint(equalTo: BlueView.leadingAnchor).isActive = true
        // myLabelのtopAnchor(最上部)の位置は、BlueViewのbottomAnchor(最下部)の位置から20pt下
        myLabel.topAnchor.constraint(equalTo: BlueView.bottomAnchor, constant: 20.0).isActive = true
        // myLabelのwidthAnchor(横幅)はBlueViewのwidthAnchor(横幅)と同じ
        myLabel.widthAnchor.constraint(equalTo: BlueView.widthAnchor).isActive = true
        // myLabelのheightAnchor(縦幅)はBlueViewのheightAnchor(縦幅)と同じ
        myLabel.heightAnchor.constraint(equalTo: BlueView.heightAnchor).isActive = true

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

 

スクリーンショット 2017-12-03 10.59.21.png

環境

  • swift
  • swift3
  • swift4
  • xcode
  • xcode9
  • mac
  • uilabel
  • constraint
  • autolayout

参考

[Swift][OSS] iOS 9以上でAuto Layoutの制約が簡潔に書けるTinyConstraintsを試してみた

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事