How do you create a UIImage View Programmatically - Swift - ios

I'm trying to create a UIImage View programmatically, I have a new view and I tried doing this
let imageName = "yourImage.png"
yourview.backgroundColor = UIColor.colorWithPatternImage(UIImage(named:imageName))
this did not work because I don't know what this should be yourview in the second line.
Question:
How do I make a UIImageView appear on the screen by coding it instead of doing it in the storyboard

First you create a UIImage from your image file, then create a UIImageView from that:
let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
Finally you'll need to give imageView a frame and add it your view for it to be visible:
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(imageView)

First create UIImageView then add image in UIImageView .
var imageView : UIImageView
imageView = UIImageView(frame:CGRectMake(10, 50, 100, 300));
imageView.image = UIImage(named:"image.jpg")
self.view.addSubview(imageView)

This answer is update to Swift 3.
This is how you can add an image view programmatically where you can control the constraints.
Class ViewController: UIViewController {
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
return theImageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(someImageView) //This add it the view controller without constraints
someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
}
// do not forget the `.isActive = true` after every constraint
func someImageViewConstraints() {
someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
}

You can use above in one line.
let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)

In Swift 3.0 :
var imageView : UIImageView
imageView = UIImageView(frame:CGRect(x:10, y:50, width:100, height:300));
imageView.image = UIImage(named:"Test.jpeg")
self.view.addSubview(imageView)

In Swift 4.2 and Xcode 10.1
//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view
//Add image view properties like this(This is one of the way to add properties).
extension UIImageView {
//If you want only round corners
func imgViewCorners() {
layer.cornerRadius = 10
layer.borderWidth = 1.0
layer.masksToBounds = true
}
}

Thanks, MEnnabah, just to add to your code where you are missing the = sign in the declaration statement:
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
return theImageView
}()
Everything else is, all perfect for Swift 3.

Make sure to put:
imageView.translatesAutoresizingMaskIntoConstraints = false
Your image view will not show if you don't put that, don't ask me why.

Swift 4:
First create an outlet for your UIImageView
#IBOutlet var infoImage: UIImageView!
Then use the image property in UIImageView
infoImage.image = UIImage(named: "icons8-info-white")

Related

UIImageView and vector images: how to adjust for zooming to avoid blurry image

I have a vector image named Link in my asset catalog (in my case contained in a pdf, setup as preserve vector data) and I use an UIImageView to show this image in my view hierarchy:
let image = UIImage(named: "Link")
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = image
And this is the simple view hierarchy:
As you can see I use .scaleAspectFit and when I set a frame for imageView the UIImageView renders the image in the desired resolution to look sharp on screen. So far so good.
In order to zoom an scroll I use an UIScrollView. After zooming in the image in the imageView appears blurry due to obviously having too low resolution for the higher zoom:
Is there any straight forward way to adjust UIImageView so that it renders the image in a higher resolution?
Discussion:
Using .scaleAspectFit the renderered image resolution resolution seems to depend on the frame set for imageView. So setting a bigger frame and scaling the view using its transform property works, but is also rather tedious.
Another way is manually rendering the image at an apporpriate solution from the vector image using UIGraphicsImageRenderer or similar. This is currenlty my preferred solution, but I am wondering if there is an easier way using UIImageView.
Here is sample code (just replace your main ViewController with this in a new project), which shows the blurry image when zooming in (just use any vector image named Link in your assets and choose render as "Template Image"):
class ViewController: UIViewController, UIScrollViewDelegate {
let contentView: UIView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 1000.0, height: 1000.0))
let scrollView: UIScrollView = {
let view = UIScrollView(frame: CGRect(x: 0.0, y: 0.0, width: 400.0, height: 400.0))
view.minimumZoomScale = 0.5
view.maximumZoomScale = 10.0
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.delegate = self
self.contentView.backgroundColor = UIColor.green.withAlphaComponent(0.2)
// setup view hierarchy
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.scrollView)
self.scrollView.addSubview(self.contentView)
// constraints
self.scrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.scrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.contentView.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor).isActive = true
self.contentView.rightAnchor.constraint(equalTo: self.scrollView.rightAnchor).isActive = true
self.contentView.topAnchor.constraint(equalTo: self.scrollView.topAnchor).isActive = true
self.contentView.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor).isActive = true
self.contentView.widthAnchor.constraint(equalToConstant: 10.0 * self.view.frame.width).isActive = true
self.contentView.heightAnchor.constraint(equalToConstant: 10.0 * self.view.frame.height).isActive = true
// setup imageView
let image = UIImage(named: "Link")
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = image
imageView.tintColor = UIColor.black
imageView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(imageView)
// add constraints
imageView.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let zoomScale = 8.0
self.scrollView.contentOffset = CGPoint(x: 0.5 * (self.contentView.frame.width - self.scrollView.frame.width), y: 0.5 * (self.contentView.frame.height - self.scrollView.frame.height))
self.scrollView.zoomScale = zoomScale
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.contentView
}
}

Custom navigation bar image and text

I need in my app a custom navigation bar with an image and a text but I can't add the text.
Here is the code to add the image, how can I add the title?
let logo = #imageLiteral(resourceName: "navigationbaricon")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
Thanks
Where is the frame assigned for self.navigationItem.titleView? Set the frame for imageView and it will work.
You can wrap the UIImageView and the UILabel (which will hold the custom title) in an UIView and then assign the UIView to the self.navigationItem.titleView. Something like this:
let view = UIView(...);
let label = UILabel(...);
label.text = "Custom Title";
let image = UIImageView(image: UIImage(named: "..."));
view.addSubview(image);
view.addSubview(label);
self.navigationItem.titleView = view;
This one is worked for me
override func viewDidLoad() {
super.viewDidLoad()
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleView.backgroundColor = UIColor.redColor()
let imageView = UIImageView(image: UIImage(named: "img")!)
imageView.frame = CGRectMake(0, 0, 40, 40)
imageView.contentMode = .ScaleAspectFill
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}

How can you change the navigation bar title to an image? Other methods have not worked

I have tried the code below and the answer to multiple other questions on Stackoverflow and I still cannot get this to work.. I know the image Profile exists in my assets folder. I have made outlets from my navigation bar and navigation item and tried using that but still got nothing. At most the text I have on the title will disappear...I feel as though I am missing something all together.
Located in ViewController's ViewDidLoad function
let image = UIImage(named: "Profile")
let imageView = UIImageView(image: image)
self.navigationItem.titleView = imageView
self.navigationItem.titleView?.sizeToFit()
Thanks for your help!
initially set the frame for imageview
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .ScaleAspectFit
if let image = UIImage(named: "Profile")
{
imageView.image = image
}else
{
imageView.image = UIImage(named: "Profile.png")
}
self.navigationItem.titleView = imageView
In Objective C:
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image];
where "image" is the instance of the image that you want to set as title view.

ImageView and Label not filling parent (UIScrollView)

I have a UIScrollView and I am trying to add a UIImageView inside the scrollview. But after that, I want a UILabel inside the imageview. Basically, the image should fill the scroll view and the label should appear in the center of the image. Here is what I have:
#IBOutlet weak var image_scroll_view: UIScrollView!
var imageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
image_scroll_view.backgroundColor = UIColor.yellowColor()
imageView.frame = CGRectMake(0, 0, image_scroll_view.frame.size.width, image_scroll_view.frame.height)
imageView.userInteractionEnabled = true
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.backgroundColor = UIColor.greenColor()
image_scroll_view.scrollRectToVisible(imageView.frame, animated: true)
self.imageView.image = // ...
let curr_user_name = UILabel(frame: CGRectMake(0, 0, imageView.frame.width, imageView.frame.height))
curr_user_name.text = "John Smith"
curr_user_name.textColor = UIColor.whiteColor()
curr_user_name.font = UIFont.boldSystemFontOfSize(16.0)
curr_user_name.backgroundColor = UIColor.redColor()
curr_user_name.center = CGPointMake(imageView.center.x, imageView.center.y)
curr_user_name.textAlignment = NSTextAlignment.Center
imageView.addSubview(curr_user_name)
image_scroll_view.addSubview(imageView)
self.navigationController?.navigationBarHidden = true
}
Here is what it looks like:
The scrollview is yellow. Ideally, the image view should fill all of that (it doesn't even show up at the moment) and the label should fill all of the image view, which would automatically center the text.
What am I doing wrong here?
make cur_user_name a property and
Write this code:
imageView.frame = CGRectMake(0, 0, image_scroll_view.frame.size.width, image_scroll_view.frame.height)
curr_user_name.center = CGPointMake(imageView.center.x, imageView.center.y)
in viewDidLayoutSubviews

How to set an image title in the navigation bar of an iOS app

I am trying to place an image logo as a title within the navigation bar of an iOS app using Swift. I included the image in the assets folder (Images.xcassets). I looked into this question but no luck.
The following is my code:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "logo") as UIImage
let imageView = UIImageView(image:logo)
imageView.frame.size.width = 200;
imageView.frame.size.height = 45;
self.navigationItem.titleView = imageView
}
...
}
I managed to create a Swift solution. Not sure if its the best way, but it works. I basically translated nerowolfe's code, and used the addSubview function.
class NavigationBar: UINavigationBar {
init(frame: CGRect) {
super.init(frame: frame)
initialise()
}
init(coder aDecoder: NSCoder!){
super.init(coder: aDecoder)
initialise()
}
func initialise(){
let logo = UIImage(named: "logo");
let imageView = UIImageView(image:logo)
imageView.frame.size.width = 145;
imageView.frame.size.height = 33;
imageView.frame.origin = CGPoint(x: 2, y: 8)
addSubview(imageView)
}
}
You are just missing a ? when you declare the image, and also may want to add a contentmode:
let logo = UIImage(named: "logo") as UIImage?
let imageView = UIImageView(image:logo)
imageView.frame.size.width = 200;
imageView.frame.size.height = 45;
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.navigationItem.titleView = imageView
Try to use addSubview method to add UIImageView to navigation bar. This is code in Objective-C:
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-vysk-white"]];
[self.navigationController.navigationBar addSubview:imgView];
imgView.contentMode = UIViewContentModeScaleAspectFit;
imgView.frame = CGRectMake(140, 0, 40, 40);

Resources