How to add subView to anotherSubView with center alignment in iOS swift. - ios

I'm using lottie library for animation. I loaded lottieFile as subView to anotherSubView but it's not aligned in center. I tried using center attributes as below:
#IBOutlet weak var viewOn: UIView!
let animationView = LOTAnimationView(name: "restless_gift_ii") {
animationView.loopAnimation = true
animationView.contentMode = .scaleToFill
animationView.animationSpeed = 1
animationView.backgroundColor = UIColor.black
animationView.frame.size = viewOn.frame.size
animationView.center.x = viewOn.center.x
animationView.center.y = viewOn.center.y
viewOn.addSubview(animationView) }

You can use auto layout programmatically to center align your animation view into it’s super view.
Here, I have added two ways to add animationView center align and also added comments for understanding.
if let animationView = LOTAnimationView(name: "4_bar_loop") {
animationView.loopAnimation = true
animationView.contentMode = .scaleToFill
animationView.animationSpeed = 1
animationView.backgroundColor = UIColor.black
self.viewOn.addSubview(animationView)
animationView.translatesAutoresizingMaskIntoConstraints = false
// Apply these constrains if you want animation size should be same as super view.
self.viewOn.addConstraint(NSLayoutConstraint(item: animationView, attribute: .leading, relatedBy: .equal, toItem: self.viewOn, attribute: .leading, multiplier: 1.0, constant: 1))
self.viewOn.addConstraint(NSLayoutConstraint(item: animationView, attribute: .trailing, relatedBy: .equal, toItem: self.viewOn, attribute: .trailing, multiplier: 1.0, constant: 1))
self.viewOn.addConstraint(NSLayoutConstraint(item: animationView, attribute: .top, relatedBy: .equal, toItem: self.viewOn, attribute:.top, multiplier: 1.0, constant: 1))
self.viewOn.addConstraint(NSLayoutConstraint(item: animationView, attribute: .bottom, relatedBy: .equal, toItem: self.viewOn, attribute: .bottom, multiplier: 1.0, constant: 1))
// Apply these constraint if you want animationView with fixed height and width and center of super view.
// self.viewOn.addConstraint(NSLayoutConstraint(item: animationView, attribute: .centerX, relatedBy: .equal, toItem: self.viewOn, attribute: .centerX, multiplier: 1.0, constant: 1))
// self.viewOn.addConstraint(NSLayoutConstraint(item: animationView, attribute: .centerY, relatedBy: .equal, toItem: self.viewOn, attribute: .centerY, multiplier: 1.0, constant: 1))
// animationView.addConstraint(NSLayoutConstraint(item: animationView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100))
// animationView.addConstraint(NSLayoutConstraint(item: animationView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100))
}

you can do it like code below programmatically i hope this help you
import UIKit
class ViewController: UIViewController {
let firstView:UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.blue
return view
}()
let secondView:UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.orange
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupViews()
}
func setupViews(){
view.addSubview(firstView)
firstView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0).isActive = true
firstView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
firstView.widthAnchor.constraint(equalToConstant: 100).isActive = true
firstView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// second view
firstView.addSubview(secondView)
secondView.centerYAnchor.constraint(equalTo: firstView.centerYAnchor, constant: 0).isActive = true
secondView.centerXAnchor.constraint(equalTo: firstView.centerXAnchor, constant: 0).isActive = true
secondView.widthAnchor.constraint(equalToConstant: 50).isActive = true
secondView.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}

#IBOutlet weak var viewOn: UIView!
let animationView = LOTAnimationView(name: "restless_gift_ii")
{
animationView.loopAnimation = true
animationView.contentMode = .scaleToFill
animationView.animationSpeed = 1
animationView.backgroundColor = UIColor.black
animationView.frame = viewOn.frame
viewOn.addSubview(animationView)
}
You can try it, hope it's OK

I was having several problems with the alignment and scaling of my Lottie animations. They would show up centered on emulator but not on devices. After debugging for hours, I found out the layout issues were happening because I was setting up the animations on the viewDidLoad(). When I moved the code to viewDidAppear(_ animated: Bool) everything worked like a charm. I hope this may help someone else.

Related

How to shadow to view to all 4 sides in swift?

I am trying to get shadow at all 4 sides, but currently getting only at 3 side.
alertCard.layer.cornerRadius = 10
alertCard.layer.shadowOffset = CGSize(width: 0, height: 5)
alertCard.layer.shadowOpacity = 0.5 //0.5
alertCard.layer.shadowRadius = 1 //3
alertCard.layer.shadowColor = yellowColor?.cgColor
Please suggest way to get shadow all 4 sides
Using UIView Extension, I managed to achieve this in one of my apps:
extension UIView {
open func generateOuterShadow() {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = layer.cornerRadius
view.layer.shadowRadius = layer.shadowRadius
view.layer.shadowOpacity = layer.shadowOpacity
view.layer.shadowColor = layer.shadowColor
view.layer.shadowOffset = CGSize.zero
view.clipsToBounds = false
view.backgroundColor = .white
superview?.insertSubview(view, belowSubview: self)
let constraints = [
NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0),
]
superview?.addConstraints(constraints)
}
}
Usage:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
shadowView.generateOuterShadow() // Add
}
Just change offSet to zero
alertCard.layer.shadowOffset = .zero
Just set shadow offset to .zero :
alertCard.layer.cornerRadius = 10
alertCard.layer.shadowOffset = .zero
alertCard.layer.shadowOpacity = 0.5
alertCard.layer.shadowRadius = 3
alertCard.layer.shadowColor = yellowColor?.cgColor

How to resolve : Unable to simultaneously satisfy constraints

I want to create like this ( Done through storyboard )
This Done through storyboard. In my observation I found the constrain problem arise from "totalAmountImg". I don't change the priority property of all objects (all have priority == 1000)
This is the result. (SummaryVC - Done this programatically)
NOTE : I want to make the SummaryVC totalAmountImg ( Programatically ) look like above image (Made by storyboard)
Stroryboard constraints for totalAmountImg
This exactly I create through code. But I don't know why this error pop out.
totalImgConstraint
func totalAmountImgConstraints() {
let imgCenterY = NSLayoutConstraint(item: totalAmountImg,
attribute: .centerY,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
imgCenterY.identifier = "imgCenterY"
imgCenterY.isActive = true
let imgRight = NSLayoutConstraint(item: totalAmountImg,
attribute: .right,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .right,
multiplier: 1.0,
constant: 16)
imgRight.identifier = "imgRight"
imgRight.isActive = true
let imgAspectRatio = NSLayoutConstraint(item: totalAmountImg,
attribute: .height,
relatedBy: .equal,
toItem: totalAmountImg,
attribute: .width,
multiplier: 1.0 / 1.0,
constant: 0)
imgAspectRatio.identifier = "imgAspectRatio"
imgAspectRatio.isActive = true
let imgLeft = NSLayoutConstraint(item: totalAmountImg,
attribute: .left,
relatedBy: .equal,
toItem: totalPriceLbl,
attribute: .right,
multiplier: 1.0,
constant: 4)
imgLeft.identifier = "imgLeft"
imgLeft.isActive = true
let imgWidth = NSLayoutConstraint(item: totalAmountImg,
attribute: .width,
relatedBy: .lessThanOrEqual,
toItem: totalAmountView,
attribute: .width,
multiplier: 0.2,
constant: 0)
imgWidth.identifier = "imgWidth"
imgWidth.isActive = true
}
SummaryVC
class SummaryVC: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageController: UIPageControl!
let numberOfPages = 3
override func viewDidLoad() {
super.viewDidLoad()
basicDesignSetup()
// Add subViews
scrollView.addSubview(summaryBaseView)
scrollView.addSubview(paymentTypeBaseView)
scrollView.addSubview(itemNameBaseView)
summaryBaseView.addSubview(totalAmountView)
summaryBaseView.addSubview(runningTableView)
summaryBaseView.addSubview(partnerAmountView)
totalAmountView.addSubview(totalLbl)
totalAmountView.addSubview(totalPriceLbl)
totalAmountView.addSubview(totalAmountImg)
view.setNeedsUpdateConstraints()
// set content size
scrollView.contentSize = CGSize(width: scrollView.frame.width * CGFloat(numberOfPages), height: scrollView.frame.height)
}
override func viewDidLayoutSubviews() {
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = scrollView.contentOffset.x / scrollView.frame.width
pageController.currentPage = Int(pageNumber)
pageController.currentPageIndicatorTintColor = UIColor.white
}
//-----------------------------------------------------------------
// MARK: - Methods
//-----------------------------------------------------------------
func basicDesignSetup() {
pageController.numberOfPages = numberOfPages
let scrollViewSize = scrollView.frame.size
let scrollViewWidth = scrollView.frame.width
// Summary View
let summeryOrigin = CGPoint(x: 0, y: 0)
summaryBaseView = UIView(frame: CGRect(origin: summeryOrigin, size: scrollViewSize))
summaryBaseView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// Payment Type View
let paymentTypeOrigin = CGPoint(x: scrollViewWidth, y: 0)
paymentTypeBaseView = UIView(frame: CGRect(origin: paymentTypeOrigin, size: scrollViewSize))
paymentTypeBaseView.backgroundColor = #colorLiteral(red: 0.01680417731, green: 0.1983509958, blue: 1, alpha: 1)
// Item Name View
let itemNameOrigin = CGPoint(x: scrollViewWidth * 2, y: 0)
itemNameBaseView = UIView(frame: CGRect(origin: itemNameOrigin, size: scrollViewSize))
itemNameBaseView.backgroundColor = #colorLiteral(red: 0, green: 0.9914394021, blue: 1, alpha: 1)
// Total Amount View
totalAmountView.backgroundColor = #colorLiteral(red: 0.5480614305, green: 0.8129847646, blue: 0.6160266995, alpha: 1)
runningTableView.backgroundColor = #colorLiteral(red: 0.4280827343, green: 0.7700845003, blue: 0.9571052194, alpha: 1)
partnerAmountView.backgroundColor = #colorLiteral(red: 0.9137254902, green: 0.4470588235, blue: 0.4549019608, alpha: 1)
totalLbl.text = "Total Amount"
totalLbl.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
totalLbl.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
totalLbl.font = UIFont.systemFont(ofSize: 16, weight: .medium)
totalPriceLbl.text = "5532.00"
totalPriceLbl.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
totalPriceLbl.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
totalAmountImg.contentMode = .scaleAspectFit
totalAmountImg.image = #imageLiteral(resourceName: "tick")
totalAmountImg.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
//-----------------------------------------------------------------
// MARK: - Views - programatically
//-----------------------------------------------------------------
// Base Views
lazy var summaryBaseView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var paymentTypeBaseView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var itemNameBaseView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// $$$$$ Summary Sub Views $$$$$
// Total Amount
lazy var totalAmountView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var totalLbl: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var totalPriceLbl: UnderlinedLabel = {
let label = UnderlinedLabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var totalAmountImg: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
// Running Table
lazy var runningTableView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var runningLbl: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var runningPriceLbl: UnderlinedLabel = {
let label = UnderlinedLabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var runningTableImg: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
// Partner Amount
lazy var partnerAmountView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var partnerLbl: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var partnerPriceLbl: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var partnerAmountImg: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
//-----------------------------------------------------------------
// MARK: - Constraints
//-----------------------------------------------------------------
override func updateViewConstraints() {
totalAmountViewConstraints()
runningTableViewConstraints()
partnerAmountViewConstraints()
// Total Amount View
totalLblConstraint()
totalPriceLblConstraints()
totalAmountImgConstraints()
super.updateViewConstraints()
}
func totalAmountViewConstraints() {
NSLayoutConstraint(item: totalAmountView,
attribute: .left,
relatedBy: .equal,
toItem: summaryBaseView,
attribute: .left,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalAmountView,
attribute: .right,
relatedBy: .equal,
toItem: summaryBaseView,
attribute: .right,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalAmountView,
attribute: .top,
relatedBy: .equal,
toItem: summaryBaseView,
attribute: .top,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalAmountView,
attribute: .bottom,
relatedBy: .equal,
toItem: runningTableView,
attribute: .top,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalAmountView,
attribute: .height,
relatedBy: .equal,
toItem: runningTableView,
attribute: .height,
multiplier: 1.0,
constant: 0).isActive = true
}
func runningTableViewConstraints() {
NSLayoutConstraint(item: runningTableView,
attribute: .leading,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: runningTableView,
attribute: .trailing,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: runningTableView,
attribute: .top,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .bottom,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: runningTableView,
attribute: .bottom,
relatedBy: .equal,
toItem: partnerAmountView,
attribute: .top,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: runningTableView,
attribute: .height,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .height,
multiplier: 1.0,
constant: 0).isActive = true
}
func partnerAmountViewConstraints() {
NSLayoutConstraint(item: partnerAmountView,
attribute: .leading,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: partnerAmountView,
attribute: .trailing,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: partnerAmountView,
attribute: .top,
relatedBy: .equal,
toItem: runningTableView,
attribute: .bottom,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: partnerAmountView,
attribute: .bottom,
relatedBy: .equal,
toItem: summaryBaseView,
attribute: .bottom,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: partnerAmountView,
attribute: .height,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .height,
multiplier: 1.0,
constant: 0).isActive = true
}
// Total Ammount Section Subviews
func totalLblConstraint() {
NSLayoutConstraint(item: totalLbl,
attribute: .top,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .top,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalLbl,
attribute: .left,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .left,
multiplier: 1.0,
constant: 16).isActive = true
NSLayoutConstraint(item: totalLbl,
attribute: .bottom,
relatedBy: .equal,
toItem: totalPriceLbl,
attribute: .top,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalLbl,
attribute: .height,
relatedBy: .equal,
toItem: totalPriceLbl,
attribute: .height,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalLbl,
attribute: .width,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .width,
multiplier: 0.7,
constant: 0).isActive = true
}
func totalPriceLblConstraints() {
NSLayoutConstraint(item: totalPriceLbl,
attribute: .top,
relatedBy: .equal,
toItem: totalLbl,
attribute: .bottom,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalPriceLbl,
attribute: .leading,
relatedBy: .equal,
toItem: totalLbl,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalPriceLbl,
attribute: .bottom,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .bottom,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalPriceLbl,
attribute: .height,
relatedBy: .equal,
toItem: totalLbl,
attribute: .height,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalPriceLbl,
attribute: .width,
relatedBy: .equal,
toItem: totalLbl,
attribute: .width,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: totalPriceLbl,
attribute: .trailing,
relatedBy: .equal,
toItem: totalLbl,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
}
func totalAmountImgConstraints() {
let imgCenterY = NSLayoutConstraint(item: totalAmountImg,
attribute: .centerY,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
imgCenterY.identifier = "imgCenterY"
imgCenterY.isActive = true
let imgRight = NSLayoutConstraint(item: totalAmountImg,
attribute: .right,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .right,
multiplier: 1.0,
constant: 16)
imgRight.identifier = "imgRight"
imgRight.isActive = true
let imgAspectRatio = NSLayoutConstraint(item: totalAmountImg,
attribute: .height,
relatedBy: .equal,
toItem: totalAmountImg,
attribute: .width,
multiplier: 1.0 / 1.0,
constant: 0)
imgAspectRatio.identifier = "imgAspectRatio"
imgAspectRatio.isActive = true
let imgLeft = NSLayoutConstraint(item: totalAmountImg,
attribute: .left,
relatedBy: .equal,
toItem: totalPriceLbl,
attribute: .right,
multiplier: 1.0,
constant: 4)
imgLeft.identifier = "imgLeft"
imgLeft.isActive = true
let imgWidth = NSLayoutConstraint(item: totalAmountImg,
attribute: .width,
relatedBy: .lessThanOrEqual,
toItem: totalAmountView,
attribute: .width,
multiplier: 0.2,
constant: 0)
imgWidth.identifier = "imgWidth"
imgWidth.isActive = true
}
//-----------------------------------------------------------------
// MARK: - Actions
//-----------------------------------------------------------------
#IBAction func pageChange(_ sender: UIPageControl) {
let x = CGFloat(sender.currentPage) * scrollView.frame.width
scrollView.contentOffset = CGPoint(x: x, y: 0)
pageController.currentPageIndicatorTintColor = UIColor.white
}
}
extension NSLayoutConstraint {
override open var description: String {
let id = identifier ?? ""
return "id: \(id), constant: \(constant)" //you may print whatever you want here
}
}
LOG
2018-01-12 16:27:27.934408+0530 Cafe Point[13577:258401] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"id: , constant: 343.0",
"id: , constant: 0.0",
"id: , constant: 0.0",
"id: , constant: 16.0",
"id: , constant: 0.0",
"id: , constant: 0.0",
"id: , constant: 0.0",
"id: imgLeft, constant: 4.0",
"id: imgRight, constant: 16.0",
"id: imgWidth, constant: 0.0"
)
Will attempt to recover by breaking constraint
id: imgLeft, constant: 4.0
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Try changing to this:
let imgRight = NSLayoutConstraint(item: totalAmountImg,
attribute: .right,
relatedBy: .equal,
toItem: totalAmountView,
attribute: .right,
multiplier: 1.0,
constant: -16)
imgRight.identifier = "imgRight"
imgRight.isActive = true
(note the 16 changes to -16)
You have to be careful when comparing constraints from the storyboard to ones created programatically because the order matters.
As the Warning states:
Will attempt to recover by breaking constraint id: imgLeft, constant:
4.0
You are giving Left and Right constraint to Image View. But also assigning Width. It confuses the Image View since Left and Right Constraints are enough to satisfy Width requirement for the Image View.
Hence you can use two combinations: left/width or right/width.
You can use other combinations too but for that, we have to dig into Priority of constraints.
To correctly understand layout keep in mind when you give a view leading/left and trailing/right constraints then you don't have to give it a width , as if you're pinning a robe to two sides , if you want to give it a width then give it a centerX constraint , Same also applied to top,bottom then don't have to give height and if you want to give height then add centerY constraint , off course you can give a view leading , trailing and width constraints at the same time but to make sure they fit together

Constraints programmatically for custom UIView in Dynamic ViewController

I'm creating new UIViewController dynamycally using this code
#IBAction func newVCBtnPressed(_ sender: Any) {
let controller = DynamicVC()
show(controller, sender: sender)
}
In the new UIViewController I'm using this code for creation of the new UIView:
override func loadView() {
view = UIView()
view.backgroundColor = .lightGray
}
In result I have view with .lightGray backgroundcolor.
I want to add custom UIView and setup the constraints programmatically, and in result i want UIView with following constraints:
top: 0
bottom:(view.frame.height*0.9)
leading:0
trailing:(view.frame.width*0.15)
width:(view.frame.width*0.85)
height:(view.frame.height*0.1)
Example:
Here is my code:
topMenuView = UIView()
topMenuView.backgroundColor = .red
view.addSubview(topMenuView)
topMenuView.translatesAutoresizingMaskIntoConstraints = false
setupConstraints(item: topMenuView, topC: 0, topToItem: view, bottomC: (view.frame.height*0.9), bottomToItem: view, widthC: (view.frame.width*0.85), heightC: (view.frame.height*0.1), leadingCon: 0, trailingCon: (view.frame.width*0.15))
I'm using this constructed function for constraints:
func setupConstraints(item:UIView, topC:CGFloat, topToItem:UIView, bottomC:CGFloat, bottomToItem:UIView, widthC:CGFloat, heightC:CGFloat, leadingCon:CGFloat, trailingCon:CGFloat) {
let topConstraint = NSLayoutConstraint(item: item, attribute: .top, relatedBy: .equal, toItem: topToItem, attribute: .bottom, multiplier: 1, constant: topC)
let bottomConstraint = NSLayoutConstraint(item: item, attribute: .bottom, relatedBy: .equal, toItem: bottomToItem, attribute: .top, multiplier: 1, constant: bottomC)
let widthConstraint = NSLayoutConstraint(item: item, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: widthC)
let heightConstraint = NSLayoutConstraint(item: item, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: heightC)
let leading = NSLayoutConstraint(item: item,attribute: .leading,relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1.0, constant: leadingCon)
let trailing = NSLayoutConstraint(item: item,attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin,multiplier: 1.0,constant: trailingCon)
view?.addConstraints([topConstraint, bottomConstraint, widthConstraint, heightConstraint, leading, trailing])
NSLayoutConstraint.activate([topConstraint, bottomConstraint, widthConstraint, heightConstraint, leading, trailing])
}
But in the result i receive only UIView with gray background, the new UIView with red background doesn't appears.
What I'm doing wrong???
You should only specify bottom OR height and width OR trailing, otherwise you are going to get conflicts here.
see playground:
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let red = UIView()
red.backgroundColor = .red
view.addSubview(red)
red.translatesAutoresizingMaskIntoConstraints = false
red.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
red.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
red.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.85).isActive = true
red.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.1).isActive = true
}
}
PlaygroundPage.current.liveView = ViewController()

Adding leading constraint programmatically crashes app

I'm trying to get my head around how adding constraints programmatically works. So far I have my code like so:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//addViewStandard()
addConstraintsView()
}
func addConstraintsView() {
let someView = UIView(frame: CGRect.zero)
someView.backgroundColor = UIColor.blue
// I want to mimic a frame set of CGRect(x: 20, y: 50, width: 50, height: 50)
let widthConstraint = NSLayoutConstraint(item: someView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
let heightConstraint = NSLayoutConstraint(item: someView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
let leadingConstraint = NSLayoutConstraint(item: someView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20)
someView.translatesAutoresizingMaskIntoConstraints = false
someView.addConstraints([widthConstraint, heightConstraint, leadingConstraint])
view.addSubview(someView)
}
}
Now when I run the app it crashes because of the leading constraint. The error message is "Impossible to set up layout with view hierarchy unprepared for constraint". What am I doing wrong here? Should I be adding the constraints to the object (the blue box on this case) or adding them to its superview?
EDIT:
After code changes I have:
func addConstraintsView() {
let someView = UIView(frame: CGRect.zero)
someView.backgroundColor = UIColor.blue
view.addSubview(someView)
someView.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: someView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
let heightConstraint = NSLayoutConstraint(item: someView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
let leadingConstraint = NSLayoutConstraint(item: someView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 20)
someView.addConstraints([widthConstraint, heightConstraint])
view.addConstraints([leadingConstraint])
}
First of all,
view.addSubview(someView)
someView.translatesAutoresizingMaskIntoConstraints = false
should come before the constraints phase; you have to apply the constraints AFTER someView is added to its superview.
Also, if you are targeting iOS 9, I'd advise you to use layout anchors like
let widthConstraint = someView.widthAnchor.constraint(equalToConstant: 50.0)
let heightConstraint = someView.heightAnchor.constraint(equalToConstant: 50.0)
let leadingConstraint = someView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0)
NSLayoutConstraint.activate([widthConstraint, heightConstraint, leadingConstraint])
This way you don't have to worry about which view to apply the constraints to.
Finally (and to clear up your doubt), if you can't use layout anchors, you should add the leading constraint to the superview, not the view.

How to create Auto layout equal width constraint programmatically in ios swift?

How to give programmatically constraints equal width and equal height with multiple views.I check google but not perfect answer for programmatically equal width and height constraints through auto layout.
my code look like below:
var countNoOfViews:Int = 3
#IBOutlet var viewForRow1: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.specialButtonViewLeft()
}
func specialButtonViewLeft(){
for i in 0..<countNoOfViews{
var customView:UIView!
customView = UIView(frame: CGRect.zero)
customView.translatesAutoresizingMaskIntoConstraints = false
viewForRow1.addSubview(customView)
let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal,toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0)
let topConstraint = NSLayoutConstraint(item: customView, attribute: .top, relatedBy: .equal,toItem: self.viewForRow1, attribute: .top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: customView, attribute: .bottom, relatedBy: .equal,toItem: self.viewForRow1, attribute: .bottom, multiplier: 1.0, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: customView, attribute: .leading, relatedBy: .equal, toItem: self.viewForRow1, attribute: .leading, multiplier: 1, constant: customLeadingSpaceLeft)
customLeadingSpaceLeft = customLeadingSpaceLeft + customViewWidth
arrayLeftBtnConstraints.append(widthConstraint)
if i == 0{
customView.backgroundColor = UIColor.red
}else if i == 1{
customView.backgroundColor = UIColor.green
}else if i == 2{
leftViewVal = customLeadingSpaceLeft
customView.backgroundColor = UIColor.black
}
customView.alpha = 0.50
viewForRow1.addConstraints([widthConstraint, leadingConstraint,topConstraint,bottomConstraint])
}
}
I want to add equal width constraint programmatically.
You have three possible ways to do that:
1) By using anchors:
view.widthAnchor.constraint(equalTo: otherView.widthAnchor, multiplier: 1.0).isActive = true
2) Visual format:
simple example - "H:|[otherView]-[view(==otherView)]|"
3) "Old school" constraints:
NSLayoutConstraint(item: #view, attribute: .width, relatedBy: .equal, toItem: #otherView, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true
hope it will help somebody.
Try this:
let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: viewForRow1, attribute: .width, multiplier: 0.25, constant: 0.0)
multiplier: 0.25, denotes that customView's width will be 1/4th of the parent view, viewForRow1.

Resources