34

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?

Lucas Azzopardi
  • 1,131
  • 2
  • 11
  • 21

7 Answers7

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)
user1333394
  • 696
  • 6
  • 6
21
let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)
Aggressor
  • 13,323
  • 24
  • 103
  • 182
  • 2
    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 style – Suhaib Sep 06 '16 at 21:27
16

Using autoview

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
mamu
  • 12,184
  • 19
  • 69
  • 92
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)
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
Lucas Azzopardi
  • 1,131
  • 2
  • 11
  • 21
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
Gasper J.
  • 481
  • 5
  • 11
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)
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)
Dennis
  • 1