how to add image view with some constraints programmatically using swift?

Related searches

I am new in iOS Development. If using storyboard, I can place an Image view in view controller like this

I need to make something like that programmatically.

so I have custom view from a library called RevealingSplashView , but I need to add an image view to that custom UI View. I just know to add the image view, maybe something like this

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
revealingSplashView.addSubview(imageView)

but I don't know how to set that constraint to image view to

a. align to center x to superview

b. proportional width to superview 0.8

c. height constraint = 25

d. align bottom to safe area = 32

how to do that ?

here is the code I use before want to add image view

let screenSize = UIScreen.main.bounds
            let iconWidth = (screenSize.width) * 0.8
            let iconHeight = iconWidth * 1 // ratio 1:1
            revealingSplashView = RevealingSplashView(iconImage: UIImage(named: "Loading Page Asset")!,iconInitialSize: CGSize(width: iconWidth, height: iconHeight), backgroundColor: AppColor.mainYellow.getUIColor())
            revealingSplashView.animationType = SplashAnimationType.twitter
            revealingSplashView.imageView?.contentMode = .scaleAspectFill


            // add loading indicator to RevealingSplashView Programatically
            revealingSplashViewIndicator.color = UIColor.white
            revealingSplashViewIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0)
            revealingSplashViewIndicator.center =  CGPoint(x: self.view.center.x, y: self.view.center.y + (iconHeight/2) + 64 )
            revealingSplashView.addSubview(revealingSplashViewIndicator)
            revealingSplashViewIndicator.bringSubviewToFront(self.revealingSplashView)
            revealingSplashViewIndicator.startAnimating()

            let window = UIApplication.shared.keyWindow
            window?.addSubview(revealingSplashView)

I recommend using anchors:

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
revealingSplashView.addSubview(imageView)

// you need to turn off autoresizing masks (storyboards do this automatically)
imageView.translatesAutoresizingMaskIntoConstraints = false

// setup constraints, it is recommended to activate them through `NSLayoutConstraint.activate`
// instead of `constraint.isActive = true` because of performance reasons
NSLayoutConstraint.activate([
    imageView.centerXAnchor.constraint(equalTo: revealingSplashView.centerXAnchor),
    imageView.widthAnchor.constraint(equalTo: revealingSplashView.widthAnchor, multiplier: 0.8),
    imageView.heightAnchor.constraint(equalToConstant: 25),
    imageView.bottomAnchor.constraint(equalTo: revealingSplashView.safeAreaLayoutGuide.bottomAnchor, constant: -32),
    ])

Using Autolayout Constraints programmatically to center a , You should use Auto Layout instead of frame for width and height of imageView; You have to add imageView to imageWrapperView before add� Now open your ViewController.swift file. There are 2 things to add image to your application programmatically. 1. Add image to your “image view”. 2. Add “image view” in your view. In viewDidLoad method write the following code to add image to your image view:

To add constraints programmatically you need to set

imageView.translatesAutoresizingMaskIntoConstraints = false

then you can set the constraints:

imageView.widthAnchor.constraint(equalTo: revealingSplashView.widthAnchor, multiplier: 0.8).isActive = true
imageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 25).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

if you want to activate constraints you need to set

isActive = true

also if you support iOS < 11 you need to put a control because you don't have the safeArea

Creating UIViews Constraints Programmatically Using PureLayout , Start by firing up Xcode -> “Create a New Xcode Project”. Select “Single View App” and press “Next”. Name the project anything you'd like, I chose to call it “ContactCard”, for no obvious reasons. Untick all three options below and, of course, choose Swift to be the programming language, then press “Next”. Programmatic Constraints. In this example, we'll center the slider horizontally. And pin it to the top of the view. We create 3 NSLayoutContraint object, one to pin to the top of the super, another to pin to the right of the super view and finally one more to pin to the right of the superview.

revealingSplashView.addSubview(imageView)

imageView.centerXAnchor.constraint(equalTo: revealingSplashView.centerXAnchor).isActive = true
imageView.widthAnchor.constraint(equalTo: revealingSplashView.widthAnchor, multiplier: 0.8).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 25).isActive = true
imageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
imageView.translatesAutoresizingMaskIntoConstraints = false

Auto Layout in Swift: Writing constraints programmatically, Auto Layout Constraints written programmatically in code by making use of Layout Anchors, Layout Guides, and a few useful extensions. Auto Layout constraints allow us to create views that dynamically adjust to different size classes You might end up with a lot of layout code in your view controllers. First of all if you want to animate a view while using constraint based layouts, you have to do something like this. self. widthConstraint. constant = 64 UIView. animate (withDuration: 0.5, animations: { self. view. layoutIfNeeded () }, completion: nil)

Adjust Image in UIImageView, The problem is I want to add constraints to the images in the image view. I added the images programmatically the code for one of the buttons looks like this: sender: Any) { goldImageView.image = UIImage(named: "gold with Text") } Xcode � Swift � Swift Playgrounds � TestFlight � Documentation � Videos � Downloads� The below screenshot should give a better understanding of constraints required for each view. And we will be adding these constraints using NSLayoutConstraint class. Pin the views to the side. Add the following code snippet that which creates Leading and Top constraint for TopLeft view. [code language=”swift”]func addtopLeftViewConstraints()

iOS, translatesAutoresizingMaskIntoConstraints = false view.addSubview(myView) // Add constraints code here // } In the examples below the Anchor Style is the� Use these guides when programmatically creating constraints to the margins or to readable content guides. Layout anchors let you create constraints in an easy-to-read, compact format. They expose a number of methods for creating different types of constraints, as shown in Listing 13-1 .

Go to contactsViewController.swift → Create a property called contactsTableView assign to a table view object by instantiating UITableView () constructor. let contactsTableView = UITableView() // view. Swift. Go to ViewDidLoad () method → Add contactsTableView as a subview of the main view.

Comments
  • unfortunately it makes crash to my app: *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x283c9b7c0 "UIImageView:0x104057cd0.bottom"> and <NSLayoutYAxisAnchor:0x283c36e40 "UILayoutGuide:0x281e48620'UIViewSafeAreaLayoutGuide'.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'
  • @Alexa289 you have to add revealingSplashView as a subview of the self.view before activating constraints.. so make sure somewhere before adding those constraints you call self.view.addSubview(revealingSplashView)
  • @Alexa289 I have updated the answer.. if there is something else you have in mind regarding the view hierarchy why this is not possible, I suggest you update the question to reflect that
  • I have tried to add your code like this: i.stack.imgur.com/uiexP.png , it is no longer crash, but I don't know why the image shows in the top of the screen like this i.stack.imgur.com/8eepT.jpg
  • @Alexa289 did you set up constraints for the revealingSplashView? it has to have constraints too.. I assumed you already did that.. update the question to show how you want to constrain the revealingSplashView
  • unfortunately it makes crash to my app, error message: *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutDimension:0x280d18f80 "UIImageView:0x10483ad70.width"> and <NSLayoutDimension:0x280d18cc0 "RevealingSplashView.RevealingSplashView:0x1048648d0.width"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'
  • did you added revealingSplashView to your view?