Swift - TableView background image: how to center the image - swift

I want to add a logo as a background image to my tableView. Image size is 50px, 50px.
I tried the code below, but this puts the image lower right corner.
let imageView = UIImageView(image: UIImage(named: "logo"))
imageView.contentMode = .scaleAspectFit
imageView.layer.frame = CGRect(x: self.view.frame.midX, y: self.view.frame.midY, width: 50, height: 50)
let tableViewBackgroundView = UIView()
tableViewBackgroundView.addSubview(imageView)
self.tableView.backgroundView = tableViewBackgroundView

There are a few points about swift that are pretty key:
1) The x and y parameters in CGRect.init(x:y:width:height:) don't refer to the center of the imageView. Instead, they are points in a coordinate system where (0, 0) is the Upper Left Corner of the view that the CGRect is being presented over, and
2) UIImageView actually inherits from UIView, so because of this you can just say
tableView.backgroundView = imageView
You shouldn't have to fiddle around with any CGRects, I believe this code should work just fine, although you may have to fiddle with different contentMode properties to get it to display how you like.
let imageView = UIImageView(image: UIImage(named: "logo"))
imageView.layer.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
imageView.layer.frame.midX = tableView.layer.frame.midX
imageView.layer.frame.midY = tableView.layer.frame.midY
tableView.backgroundView = imageView

Related

How to overlay an image on top of another image

I am working on creating a small word guessing app for a school assignment in uikit and I have been trying to figure out a way to overlay an image that updates based on the amount of incorrect guesses left on top of another image. I've spent almost 2 1/2 hours checking and I could not find a single method that worked.
So far this is what I've tried
let bgimg = UIImage(named: "background") // The image used as a background
let bgimgview = UIImageView(image: bgimg) // Create the view holding the image
bgimgview.frame = CGRect(x: 0, y: 0, width: 500, height: 500) // The size of the background image
let frontimg = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)") // The image in the foreground
let frontimgview = UIImageView(image: frontimg) // Create the view holding the image
frontimgview.frame = CGRect(x: 150, y: 300, width: 50, height: 50) // The size and position of the front image
bgimgview.addSubview(frontimgview) // Add the front image on top of the background
I commented this one out so that my code could work
let bottomImage = UIImage(named: "background")!
// let topImage = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)")!
// let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
// let newSize = rect.size // set this to what you need
// UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
//
// bottomImage.draw(in: rect)
// topImage.draw(in: rect)
//
// let newImage = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
// }
//
// var backgroundImageButton: UIButton! {
// backgroundImageButton.setBackgroundImage(newImage)
You should be able to do this by adjusting the alpha value of the foreground image view. Alpha controls the transparency of a view-- an alpha of 1.0 makes it opaque, a value of 0 is invisible, and values between 0 and 1 make a view more or less transparent. If you have the two image views aligned so that one covers the other, you can set the foreground image alpha to any value from 0 to 1 to adjust how transparent it is.

UIImage in a UIcollectonView issue

I am trying to add a UIImage to the UICollectionViewController by using the following code:
let backgroundImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 430, height: 550))
backgroundImage.image = UIImage(named: "fantasy_football_hero_tile_cropped.png")
backgroundImage.contentMode = UIView.ContentMode.scaleAspectFit
backgroundImage.clipsToBounds = true
self.view.insertSubview(backgroundImage, at: 0)
My issue is that the image is not at the bottom/lowest part of the screen which is what I am trying to achieve... how can I clip it to the bottom?! I am not using story board, can I programmatically anchor the image to the bottom as I could do in a storyboard?
This is especially true since the screen sizes for the phones are different, but the desire is still to have it anchored to the bottom.
you can add programatically. I think you add/insert some views to the self.view that will also affect simple scenario
let backgroundImageV = UIView(frame: CGRect(x: 0, y: 0, width: 430, height: 500))
backgroundImageV.backgroundColor = UIColor.blue
backgroundImageV.contentMode = UIView.ContentMode.scaleAspectFit
backgroundImageV.clipsToBounds = true
self.view.addSubview(backgroundImageV)
let backgroundImageV2 = UIView(frame: CGRect(x: 0, y: 0, width: 430, height: 510))
backgroundImageV2.backgroundColor = UIColor.green
backgroundImageV2.contentMode = UIView.ContentMode.scaleAspectFit
backgroundImageV2.clipsToBounds = true
self.view.insertSubview(backgroundImageV2, at: 0)
let backgroundImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 430, height: 550))
backgroundImage.backgroundColor = UIColor.red
backgroundImage.contentMode = UIView.ContentMode.scaleAspectFit
backgroundImage.clipsToBounds = true
self.view.insertSubview(backgroundImage, at: 0)
Here Red will be bottom Green will be in 1. because you add that red colored view later. So It will work. Can you please show your full code. It will work
One problem here is that self.view for a UICollectionViewController is the UICollectionView. This is a scroll view, so no matter where you put this image view, it is going to move when the scroll view scrolls.
If that isn't what you want, there is a simple solution: set the image view as the collection view's backgroundView. That is a stationary view that forms the background to the collection view no matter how it is scrolled. If you set the image view's contentMode to bottom the image will be centered at the bottom, which seems to be what you are after.

How to change the size of the titleView of Navigation Item? (Swift)

In my app I want to change the titleView of my Navigation Controller to a custom ImageView but I have a very strange problem. I basically just can`t set the frame of my ImageView.
This is my code:
func NavBarEinrichten(){
let logo = UIImage(named: "Notennamen für Griffe 1")!
let imageView = UIImageView(image:logo)
imageView.contentMode = .scaleAspectFit
//To show the problem better
imageView.backgroundColor = UIColor.red
let navController = navigationController!
let bannerWidth:CGFloat = 20
let bannerHeight:CGFloat = navController.navigationBar.frame.size.height
let bannerX = bannerWidth / 2 - logo.size.width / 2
let bannerY = bannerHeight / 2 - logo.size.height / 2
imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
self.navigationItem.titleView?.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
navigationItem.titleView = imageView
print(imageView.frame, "imageView frame")
}
The print statement prints:
(0.0, 0.0, 357.0, 142.0) imageView frame
Which is right, because it looks like this when i run it, but not like it should be. Because I want the width to be 20.
In the simulator it looks like this:
I tried to call this method in viewDidLoad(), viewWillAppear()and viewDidLayoutSubviews()
Every time with the exact same outcome...
Can you help me?

Facebook Picture zoom animation in swift, picture not showing the initial position

I've been trying to make a zoom animation like Facebook when you click a picture into a cell to move into the middle of the screen. The animation works, but for a reason that I can not figure out, it is not starting from the initial position it is giving me another frame. Please help, I've been struggling with this for a few days now.
I am using a collectionView with CustomCell and everything it's done programmatically:
The function in CenterVC:
//MARK: Function to animate Image View (it will animate to the middle of the View)
func animateImageView(statusImageView : UIImageView) {
//Get access to a starting frame
statusImageView.frame.origin.x = 0
if let startingFrame = statusImageView.superview?.convert(statusImageView.frame, to: nil) {
//Add the view from cell to the main view
let zoomImageView = UIView()
zoomImageView.backgroundColor = .red
zoomImageView.frame = statusImageView.frame
view.addSubview(zoomImageView)
print("Starting frame is: \(startingFrame)")
print("Image view frame is: \(statusImageView.frame)")
UIView.animate(withDuration: 0.75, animations: {
let height = (self.view.frame.width / startingFrame.width) * startingFrame.height
let y = self.view.frame.height / 2 - (height / 2)
zoomImageView.frame = CGRect(x: 0, y: y, width: self.view.frame.width, height: height)
})
}
}
This is the pictureView inside the cell and the constraints (this is where I am setting up the picture for the view, and I am using in cellForRowAtIndexPath cell.centerVC = self):
var centerVC : CenterVC?
func animate() {
centerVC?.animateImageView(statusImageView: pictureView)
}
let pictureView : UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = UIImage(named: "cat")
imageView.backgroundColor = UIColor.clear
imageView.layer.masksToBounds = true
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
addConstraintsWithFormat(format: "V:|-5-[v0(40)]-5-[v1]-5-[v2(200)]", views: profileImage, postTextView, pictureView)
addConstraintsWithFormat(format: "H:|[v0]|", views: pictureView)
This is what it prints out in the debugger:
Starting frame is: (5.0, 547.5, 365.0, 200.0)
Image view frame is: (0.0, 195.5, 365.0, 200.0)
As you can see the starting frame it's different from the initial frame and position of the picture. The animation it's not leaving the initial position it just appears somewhere on top and animates to the middle. I don't know what to do, please advice.
For some reason, it was not reading the starting frame rect so I've made a new CGRect that gets the origin and set the size of the picture: (it animates perfectly now)
zoomImageView.frame = CGRect(origin: startingFrame.origin, size: CGSize(width: view.frame.width, height: statusImageView.frame.height))

Insert CAShapeLayer behind Image in UIImageView

Just as the title says. I have a UIImageView and I am inserting CAShapeLayers into the View. The issue is that I don't know how to insert them behind the image of the UIImageView. Any advice would be much appreciated, thanks.
You could try to do some layer re-ordering, but you might be foiled by UIImageView's own internal code. My suggestion would be be to create a container view and add your sublayers there, then add the image view as a subview (which is essentially adding it as a sublayer as well). As long as the image has transparency and the UIImageView is not opaque, it will work.
This code worked for me in a playground:
let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let imageView = UIImageView(frame: container.bounds)
imageView.image = UIImage(named: "duck.png")
imageView.isOpaque = false
let shape = CAShapeLayer()
shape.path = UIBezierPath(roundedRect: container.bounds, cornerRadius: 2).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.lineWidth = 10
shape.fillColor = UIColor.blue.cgColor
shape.borderColor = UIColor.black.cgColor
container.layer.addSublayer(shape)
container.addSubview(imageView)
Good luck!