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

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

Related

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

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.

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

How to make a view scroll against a scrollview animation?

So I have a UIView and I want to have it animate a translation in the opposite direction of the scrollviews scroll animation. How would I go about doing this? Of course this should be depend on the scrollview.contentOffset I think anyway. So if you scroll the other way it goes back to it's place. So the translation is dependent on how far the user scrolls. I am trying to use the following code. Also note that the UIView I currently do not have as a child of the scrollview. It is suppose to stay on screen at all time, but change positions.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x >= scrollView.contentSize.width {
UIView.animate(withDuration: 2.0, animations: {
self.view.layoutIfNeeded()
})
}
A simple solution would be:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let percentage = scrollView.contentOffset.x / scrollView.contentSize.width
self.box.frame.origin.x = UIScreen.main.bounds.width * percentage
}
Just calculate the percentage of the contentSize that you have scrolled and set the X position to the same percentage of the screen width.
It could do with some improvements to make sure the view doesn't go beyond the bounds of the screen in certain conditions. So you may need to factor in the width of the box in the calculations as an enhancement.
Here is the code I used for testing, The background image is a 4K wallpaper image.
class ViewController: UIViewController {
var box = UIView()
var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView = UIScrollView()
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.delegate = self
self.view.addSubview(self.scrollView)
NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "background")
self.scrollView.addSubview(imageView)
NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: scrollView, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: imageView, attribute: .right, relatedBy: .equal, toItem: scrollView, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
box.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 110, width: 100, height: 100)
box.backgroundColor = .black
self.view.addSubview(box)
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let percentage = scrollView.contentOffset.x / scrollView.contentSize.width
let xPosition = UIScreen.main.bounds.width * percentage
self.box.frame.origin.x = xPosition
}
}

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.

UIVisualEffectView not working

I'm trying to add a blur effect to my view using the following code :
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = containerView.bounds
containerView.addSubview(visualEffectView)
containerView.userInteractionEnabled = true
containerView.bringSubviewToFront(visualEffectView)
visualEffectView.alpha = 1.0
However, I do not see any changes.
UPDATE
My apologies, but I don't think I made my intentions clear in the original question. What I want to achieve is something like this :
My view holds a UIImageView which fills the whole screen. Next, on the bottom of the screen, I have a container which is a UIView which holds some buttons etc. What I want to do is add a blur effect to the containerView, so that the UIImageView behind it is blurred, where the containerView is. So basically I set my containerView's alpha to 0.5, which means its semi transparent and I can see the image behind it. What I want to do now is for that image behind the containerView to be blurred.
CURRENT EFF :
CODE :
extension UIButton{
func setImage(image: UIImage?, inFrame frame: CGRect?, forState state: UIControlState){
self.setImage(image, forState: state)
if let frame = frame{
self.imageEdgeInsets = UIEdgeInsets(
top: frame.minY - self.frame.minY,
left: frame.minX - self.frame.minX,
bottom: self.frame.maxY - frame.maxY,
right: self.frame.maxX - frame.maxX
)
}
}
}
class SingleImageFeedView: UIViewController {
lazy var mainImageView : UIImageView = {
let imageView = UIImageView()
imageView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.width * 1.3)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.backgroundColor = UIColor.clearColor()
imageView.image = UIImage(named: "pizza")
return imageView
}()
let containerView : UIView = {
let this = UIView(frame: CGRectMake(0,0, 600,150))
this.backgroundColor = UIColor.clearColor()
this.layer.cornerRadius = 5
this.layer.borderColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 1.0).CGColor
this.layer.borderWidth = 0.5
return this
}()
let captionAndProfileImageContainerView : UIView = {
let this = UIView()
//this.backgroundColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 0.0)
this.backgroundColor = UIColor.clearColor()
return this
}()
let profilePicImageView : UIImageView = {
let imageView = UIImageView()
imageView.frame = CGRectMake(0, 0, 53, 53)
imageView.backgroundColor = UIColor.clearColor()
imageView.image = UIImage(named: "pizza")
imageView.contentMode = UIViewContentMode.ScaleToFill
return imageView
}()
let captionTextView: UITextView = {
let textField = UITextView(frame: CGRectMake(0,0, 150, 100))
textField.textColor = UIColor.whiteColor()
textField.editable = false
textField.text = "dwwdwwwwdwddwd"
textField.backgroundColor = UIColor.clearColor()
textField.font = UIFont.systemFontOfSize(12.0)
return textField
}()
let dividerLineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
return view
}()
let commentAndLikesContainerView : UIView = {
let view = UIView()
//view.backgroundColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 0.0)
view.backgroundColor = UIColor.clearColor()
return view
}()
let commentLabel : UILabel = {
let label = UILabel()
label.text = "23"
return label
}()
let likesLabel : UILabel = {
let label = UILabel()
label.text = "25"
return label
}()
let voteUpButton : UIButton = {
let button = UIButton(frame: CGRectMake(0,0,25,25))
button.setImage((scaleImage((UIImage(named: "upvote"))!, toSize: CGSizeMake(25, 25))), inFrame: CGRectMake(0,0,25,25), forState: .Normal)
button.imageView?.contentMode = UIViewContentMode.Center
button.imageView?.clipsToBounds = true
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
return button
}()
let voteDownButton : UIButton = {
let button = UIButton(frame: CGRectMake(0,0,25,25))
button.setImage((scaleImage((UIImage(named: "upvote"))!, toSize: CGSizeMake(25, 25))), inFrame: CGRectMake(0,0,25,25), forState: .Normal)
button.imageView?.transform = CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 180.0)
button.imageView?.contentMode = UIViewContentMode.Center
button.imageEdgeInsets = UIEdgeInsetsMake(6, 10, 10, 10)
button.imageView?.clipsToBounds = true
return button
}()
let commentButton : UIButton = {
let button = UIButton(frame: CGRectMake(0,0,25,25))
button.setImage((scaleImage((UIImage(named: "comment_feed_icon"))!, toSize: CGSizeMake(25, 25))), inFrame: CGRectMake(0,0,25,25), forState: .Normal)
button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
button.imageView?.clipsToBounds = true
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
setupViews()
}
func setupViews() {
self.captionAndProfileImageContainerView.addSubview(profilePicImageView)
self.captionAndProfileImageContainerView.addSubview(captionTextView)
self.commentAndLikesContainerView.addSubview(voteUpButton)
self.commentAndLikesContainerView.addSubview(voteDownButton)
self.commentAndLikesContainerView.addSubview(commentButton)
self.commentAndLikesContainerView.addSubview(commentLabel)
self.commentAndLikesContainerView.addSubview(likesLabel)
self.containerView.addSubview(captionAndProfileImageContainerView)
self.containerView.addSubview(dividerLineView)
self.containerView.addSubview(commentAndLikesContainerView)
self.view.addSubview(containerView)
self.view.bringSubviewToFront(containerView)
self.view.addSubview(mainImageView)
self.containerView.bringSubviewToFront(captionAndProfileImageContainerView)
self.containerView.bringSubviewToFront(dividerLineView)
self.containerView.bringSubviewToFront(commentAndLikesContainerView)
profilePicImageView.translatesAutoresizingMaskIntoConstraints = false
captionTextView.translatesAutoresizingMaskIntoConstraints = false
voteDownButton.translatesAutoresizingMaskIntoConstraints = false
containerView.translatesAutoresizingMaskIntoConstraints = false
voteUpButton.translatesAutoresizingMaskIntoConstraints = false
commentLabel.translatesAutoresizingMaskIntoConstraints = false
commentButton.translatesAutoresizingMaskIntoConstraints = false
commentAndLikesContainerView.translatesAutoresizingMaskIntoConstraints = false
captionAndProfileImageContainerView.translatesAutoresizingMaskIntoConstraints = false
likesLabel.translatesAutoresizingMaskIntoConstraints = false
dividerLineView.translatesAutoresizingMaskIntoConstraints = false
mainImageView.translatesAutoresizingMaskIntoConstraints = false
//main imageview constraints
self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 35))
self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0))
self.view.sendSubviewToBack(mainImageView)
//containerview constraints
self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -10))
self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: -10))
self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -160))
//caption and profilepic constraints
self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: -50))
self.view.addConstraintsWithFormat("H:|-8-[v0(50)]", views: profilePicImageView)
self.view.addConstraintsWithFormat("V:|-35-[v0(50)]", views: profilePicImageView)
profilePicImageView.layer.cornerRadius = 25
profilePicImageView.layer.masksToBounds = true
self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Top, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Leading, relatedBy: .Equal, toItem: profilePicImageView, attribute: .Trailing, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Trailing, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Bottom, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Bottom, multiplier: 1, constant: 0))
//likes and comments and divider
self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Top, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Bottom, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: voteUpButton, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: voteUpButton, attribute: .Leading, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Leading, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: likesLabel, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: likesLabel, attribute: .Leading, relatedBy: .Equal, toItem: voteUpButton, attribute: .Trailing, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: voteDownButton, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: voteDownButton, attribute: .Leading, relatedBy: .Equal, toItem: likesLabel, attribute: .Trailing, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: commentButton, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: commentButton, attribute: .Leading, relatedBy: .Equal, toItem: voteDownButton, attribute: .Trailing, multiplier: 1, constant: 30))
self.view.addConstraint(NSLayoutConstraint(item: commentLabel, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: commentLabel, attribute: .Leading, relatedBy: .Equal, toItem: commentButton, attribute: .Trailing, multiplier: 1, constant: 10))
if !UIAccessibilityIsReduceTransparencyEnabled() {
self.containerView.backgroundColor = UIColor.clearColor()
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
//always fill the view
blurEffectView.frame = containerView.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.containerView.insertSubview(blurEffectView, atIndex: 1) //if you have more UIViews, use an insertSubview API to place it where needed
}
else {
self.view.backgroundColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 0.5)
}
containerView.clipsToBounds = true
}
}
I made a simple project with a UIImageView and and a container. Applying the blur to the container blurred the underneath photo. The containers background is set to transparent in storyboard.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let containerView : UIView = {
let this = UIView(frame: CGRectMake(100,200, 200,200))
this.backgroundColor = UIColor.clearColor()
this.layer.cornerRadius = 5
this.layer.borderColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 1.0).CGColor
this.layer.borderWidth = 0.5
return this
}()
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
visualEffectView.frame = containerView.bounds
self.view.addSubview(containerView)
containerView.insertSubview(visualEffectView, atIndex: 0)
let secondImg = UIImageView(image: UIImage(named: "swift_tut.png"))
secondImg.frame = CGRectMake(150,250, 200,200)
self.view.addSubview(secondImg)
self.view.bringSubviewToFront(containerView)
// Do any additional setup after loading the view, typically from a nib.
}
Try This Code , working for me
if !UIAccessibilityIsReduceTransparencyEnabled() {
self.view.backgroundColor = UIColor.clearColor()
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
//always fill the view
blurEffectView.frame = self.view.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.view.insertSubview(blurEffectView, atIndex: 1) //if you have more UIViews, use an insertSubview API to place it where needed
}
else {
self.view.backgroundColor = UIColor.blackColor()
}

Resources