実は制約も部品のようにアウトレット接続が可能なのです。自分的メモなのでザックリ掲載。
制約をコードから操作するシンプルなデモ
黄色いラベルの横サイズとスーバービューとの上マージンを操作しています。緑のLabelには黄色いLabelとのマージンとEqual Bottomが指定されているので黄色いラベルの移動に伴って一緒に移動します。
ViewController.swift
//
// ViewController.swift
// Constraint
//
import UIKit
class ViewController: UIViewController {
var toggle1:Bool = true
var toggle2:Bool = true
var toggle3:Bool = true
@IBOutlet weak var label1:UILabel!
@IBOutlet var constraintLabelWidth:NSLayoutConstraint!
@IBOutlet var constraintLabelTopMargin:NSLayoutConstraint!
@IBAction func changeConstraint(_ sender:UIButton){
toggle1 = toggle1 ? false : true
let value:CGFloat = toggle1 ? 100 : -100
constraintLabelWidth.constant += value
}
@IBAction func changeConstraintWithAnimation(_ sender:UIButton){
toggle2 = toggle2 ? false : true
let value:CGFloat = toggle2 ? 100 : -100
self.view.removeConstraint(constraintLabelWidth)
constraintLabelWidth.constant += value
label1.addConstraint(constraintLabelWidth)
UIView.animate(
withDuration: 1.0,
delay:0.5,
options:UIViewAnimationOptions.curveEaseOut,
animations: {() -> Void in
self.view.layoutIfNeeded()
},
completion: nil
)
}
@IBAction func changeConstraintTopMarginWithAnimation(_ sender:UIButton){
toggle3 = toggle3 ? false : true
let value:CGFloat = toggle3 ? 100 : -100
self.view.removeConstraint(constraintLabelTopMargin)
constraintLabelTopMargin.constant += value
view.addConstraint(constraintLabelTopMargin)
UIView.animate(
withDuration: 0.5,
delay:0.0,
options:UIViewAnimationOptions.curveEaseOut,
animations: {() -> Void in
self.view.layoutIfNeeded()
},
completion: nil
)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}