斯威夫特 - 我很愚蠢,我的子视图不会服从并正确调整自己的大小

时间:2020-12-26 20:13:38

I feel like this is a softball for you veterans, but I'm having a lot of trouble resizing the subview of my UIImageView... here is what I got:

我觉得这对你的老兵来说是一个垒球,但是我在调​​整UIImageView的子视图时遇到了很多麻烦......这就是我得到的:

var myImageView:UIImageView!

var tmpView:UIImageView!

myImageView is my "main" UIImageView, and I'm treating tmpView as a subview... now I've tried both with and without auto layout on, but I've set the constraints of myImageView s.t. myImageView takes up the whole screen. I've confirmed this to be true by setting myImageView.image = UIImage...etc.

myImageView是我的“主要”UIImageView,我将tmpView视为一个子视图......现在我已经尝试过使用和不使用自动布局,但我已经设置了myImageView s.t的约束。 myImageView占据整个屏幕。我通过设置myImageView.image = UIImage等来证实这是真的。

Here is my code for initializing the image and adding it to the subview:

这是我的代码,用于初始化图像并将其添加到子视图:

self.tmpView.image = UIImage(named: "myImage.png")
self.tmpView.frame = CGRect(x: 0, y: 0, width: 200, height: 300)
self.imageView2.addSubview(self.tmpView)

Now here is where I am running into problems - no matter what I set tmpView's height and width to, the size never changes. Interestingly though, changing x,y does have an effect on the position of the subview.

现在我遇到了问题 - 无论我设置tmpView的高度和宽度,大小都不会改变。有趣的是,改变x,y确实会对子视图的位置产生影响。

Here are my questions: 1) Why do both x and y obey nicely, but width and height do not?

以下是我的问题:1)为什么x和y都很好地服从,但宽度和高度却没有?

2) How do I fix this, and is it best to do so programmatically or through the storyboard?

2)如何解决这个问题,最好是以编程方式还是通过故事板进行修复?

1 个解决方案

#1


0  

You should no longer modify the frames directly when using autolayout. Add a width and height constraint to tmpView, and create outlets for them if you're using IB (The outlets should have the type NSLayoutContraint).

使用autolayout时,不应再直接修改帧。向tmpView添加宽度和高度约束,如果您正在使用IB,则为它们创建出口(出口应具有类型NSLayoutContraint)。

You can also create the constraints in code but there's no point of doing it that way unless you have to.

您也可以在代码中创建约束,但除非必须,否则没有必要这样做。

In both cases, to resize tmpView, change the constant property of each of the constraints to the values you want.

在这两种情况下,要调整tmpView的大小,请将每个约束的常量属性更改为所需的值。

widthConstraint.constant = yourNewWidth;
heightConstraint.constant = yourNewHeight;

#1


0  

You should no longer modify the frames directly when using autolayout. Add a width and height constraint to tmpView, and create outlets for them if you're using IB (The outlets should have the type NSLayoutContraint).

使用autolayout时,不应再直接修改帧。向tmpView添加宽度和高度约束,如果您正在使用IB,则为它们创建出口(出口应具有类型NSLayoutContraint)。

You can also create the constraints in code but there's no point of doing it that way unless you have to.

您也可以在代码中创建约束,但除非必须,否则没有必要这样做。

In both cases, to resize tmpView, change the constant property of each of the constraints to the values you want.

在这两种情况下,要调整tmpView的大小,请将每个约束的常量属性更改为所需的值。

widthConstraint.constant = yourNewWidth;
heightConstraint.constant = yourNewHeight;