Programmatically change the height and width of a UIImageView Xcode Swift
Asked Answered
S

7

36

Hey for some reason I am struggling with trying to set the height and width of one of my image views. I want to set it so the height only goes for 20% of my screen. I know to regularly set it you can do things like: image = (0,0,50,50)

But I need the height to not be a static number. Something like image = (0,0, frame.height * 0.2, 50)

Any suggestions?

Savill answered 10/7, 2015 at 16:30 Comment(0)
G
54

The accepted answer in Swift 3:

let screenSize: CGRect = UIScreen.main.bounds
image.frame = CGRect(x: 0, y: 0, width: 50, height: screenSize.height * 0.2)
Gambrell answered 8/2, 2017 at 17:15 Comment(1)
man thank you the screen thing fixed imageView not abiding .scaleAspectFit ruleFebruary
B
21
let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)
Brantbrantford answered 10/7, 2015 at 16:41 Comment(1)
You can do the above code this wayy too image.frame = CGRect(0,0, screenSize.height * 0.2, 50) The difference is that this way it looks more swift. CGRectMake is Objective-C styleReconstruct
M
19

Using autoview

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
Monobasic answered 1/6, 2018 at 14:46 Comment(1)
it was a suitable answer for meWilk
S
5

Hey i figured it out shortly after. For some reason I was just having a brain fart.

image.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.2)
Savill answered 10/7, 2015 at 16:40 Comment(0)
P
4

A faster / alternative way to change the height and/or width of a UIView is by setting its width/height through frame.size:

let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight
Person answered 19/2, 2020 at 8:50 Comment(0)
J
2

u can use this code

var imageView = UIImageView(image: UIImage(name:"imageName"));
imageView.frame = CGrectMake(x,y imageView.frame.width*0.2,50);

or

var imageView = UIImageView(frame:CGrectMake(x,y, self.view.frame.size.width *0.2, 50)
Jackelinejackelyn answered 10/7, 2015 at 16:46 Comment(0)
T
0

imageView is a subview of the main view. It works this way

image.frame = CGRectMake(0 , 0, super.view.frame.width, super.view.frame.height * 0.2)
Trichomonad answered 5/3, 2018 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.