简体   繁体   English

以编程方式设置Swift元素的位置

[英]Programmatically set position of Swift element

I have a label defined in Storyboard and I'm trying to change its position based programatically. 我在Storyboard中定义了一个标签,我试图以编程方式更改其位置。 There are some existing questions on SO already that seem to address this issue, but none of the solutions seem to work (ie, the label doesn't move). 关于SO的一些现有问题似乎已经解决了这个问题,但是没有一个解决方案似乎有效(即标签不会移动)。 I've removed all existing constraints on the label to no avail. 我删除了标签上的所有现有约束无济于事。 I've tried: 我试过了:

class LandingViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        titleLabel.frame = CGRectMake(100, 25, titleLabel.frame.size.width, titleLabel.frame.size.height)
        }

I also tried 我也试过了

titleLabel.center = CGPointMake(120, 150)

instead of titleLabel.frame 而不是titleLabel.frame

Am I missing something? 我错过了什么吗?

When using AutoLayout, views instantiated in storyboards with constraints have their translatesAutoresizingMaskIntoConstraints property set to false , in contrast to views instantiated programmatically. 使用AutoLayout时,在具有约束的故事板中实例化的视图将其translatesAutoresizingMaskIntoConstraints属性设置为false ,与以编程方式实例化的视图相反。 This is because interface builder expects constraints to fully specify the layout of that view. 这是因为接口构建器期望约束完全指定该视图的布局。

To modify your frame/bounds/center manually, set this property to true in code. 要手动修改框架/边界/中心,请在代码中将此属性设置为true This will make the view's layout behave in a way similar to how things worked in the days before AutoLayout, so be aware that any constraints you specify on the view may conflict or behave unexpectedly if you just specify this property when you actually want it to be laid out using constraints. 这将使视图的布局行为类似于AutoLayout之前的工作方式,因此请注意,如果您只是在实际需要时指定此属性,则您在视图上指定的任何约束都可能会发生冲突或出现意外行为使用约束布局。

I would suggest that you first consider whether what you actually want to do is specify your label's position through AutoLayout constraints. 我建议您首先考虑一下您实际想要做的是通过AutoLayout约束来指定标签的位置。 These days, it is rare that you actually want to specify a position manually, as you have done above. 现在,您实际上想要手动指定一个位置是很少见的,就像您上面所做的那样。

Do you want to center the label according the screen size? 您想根据屏幕尺寸使标签居中吗? if so, try the below (Note the UIlabel is created programmatically) 如果是这样,请尝试以下(注意UIlabel是以编程方式创建的)

 var tempLabel:UILabel
 override func viewDidLoad() {
      super.viewDidLoad()

     //gets screen frame size
     var fm: CGRect = UIScreen.mainScreen().bounds

     //creates a temp UILabel
     tempLabel = UILabel(frame:  CGRectMake(0, fm.frame.size.height, fm.size.width, fm.size.height))

     //aligns the UIlabel to center
     tempLabel.textAlignment = NSTextAlignment.Center

    //adding UIlabel to view
    view.addSubview(tempLabel)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM