xcode 在 Swift 中以编程方式定位对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29940621/
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-09-15 07:05:17  来源:igfitidea点击:

Positioning of object programmatically in Swift

iosxcodeswift

提问by Orkhan Alizade

I want to set a position of an object programmatically. For this I do:

我想以编程方式设置对象的位置。为此,我这样做:

youtubeIco.frame.origin.y = 100

but nothing. It doesn't change coordinates at all. What is the problem?

但没什么。它根本不会改变坐标。问题是什么?

And a second question:

还有第二个问题:

when I set in the XCode constraints of webView(for ex: 10(top, left, right, bottom) it disappears. But when I do not set constraints for it, it appears. What is the problem?

当我在 webView 的 XCode 约束中设置时(例如:10(上,左,右,下)它消失了。但是当我没有为它设置约束时,它会出现。有什么问题?

I want like this:

我想要这样:

enter image description here

在此处输入图片说明

回答by Viral Savaj

You need to set full frame like,

您需要设置全帧,例如,

youtubeIco.frame = CGRectMake(youtubeIco.frame.origin.x, 100,youtubeIco.frame.size.width,youtubeIco.frame.size.height)

Only y-axis change will not do anything to it, you have to provide full frame for that. or set centre, or offset.

只有 y 轴变化不会对其产生任何影响,您必须为此提供完整的框架。或设置中心,或偏移。

回答by Duncan C

With AutoLayout you can't change a view's frame directly. The constraint puts the object right back where it was.

使用 AutoLayout 您不能直接更改视图的框架。约束将对象放回原来的位置。

Instead, you should add constraints that position your views and add IBOutlets to those constraints. Then you use the outlet(s) to change the constant value of the constraint, and the constraint moves your view objects for you. (In this context anything you can display on the screen is a view {a descendant of UIView} including buttons.)

相反,您应该添加定位视图的约束并将 IBOutlets 添加到这些约束。然后你使用出口来改变约束的常量值,约束会为你移动你的视图对象。(在这种情况下,您可以在屏幕上显示的任何内容都是一个视图{UIView 的后代},包括按钮。)