ios 以编程方式更改 UIImageView Xcode Swift 的高度和宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31345903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:48:57  来源:igfitidea点击:

Programmatically change the height and width of a UIImageView Xcode Swift

iosxcodeswiftuiimageview

提问by Lucas Azzopardi

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)

嘿,出于某种原因,我正在努力尝试设置我的一个图像视图的高度和宽度。我想将其设置为高度仅占屏幕的 20%。我知道要定期设置它,您可以执行以下操作: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)

但我需要高度不是一个静态数字。像 image = (0,0, frame.height * 0.2, 50)

Any suggestions?

有什么建议?

回答by user1333394

The accepted answer in Swift 3:

Swift 3 中接受的答案:

let screenSize: CGRect = UIScreen.main.bounds
image.frame = CGRect(x: 0, y: 0, width: 50, height: screenSize.height * 0.2)

回答by Aggressor

let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)

回答by mamu

Using autoview

使用自动查看

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true

回答by Lucas Azzopardi

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)

回答by Konstantin Kryzhanovsky

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)

回答by Gasper J.

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

更改 a 的高度和/或宽度的更快/替代方法UIView是将其宽度/高度设置为frame.size

let neededHeight = UIScreen.main.bounds * 0.2
yourView.frame.size.height = neededHeight

回答by Dennis

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

imageView 是主视图的子视图。它是这样工作的

image.frame = CGRectMake(0 , 0, super.view.frame.width, super.view.frame.height * 0.2)