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

时间:2015-07-19 16:51:58

标签: ios swift

我在Storyboard中定义了一个标签,我正在尝试以编程方式更改其位置。关于SO的一些现有问题似乎已经解决了这个问题,但是没有一个解决方案似乎有效(即标签不会移动)。我删除了标签上的所有现有约束无济于事。我试过了:

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)
        }

我也试过

titleLabel.center = CGPointMake(120, 150)

而不是titleLabel.frame

我错过了什么吗?

2 个答案:

答案 0 :(得分:5)

使用AutoLayout时,在具有约束的故事板中实例化的视图将translatesAutoresizingMaskIntoConstraints属性设置为false,与以编程方式实例化的视图相反。这是因为接口构建器期望约束完全指定该视图的布局。

要手动修改帧/边界/中心,请在代码中将此属性设置为true。这将使视图的布局行为类似于AutoLayout之前的工作方式,因此请注意,如果只是在<时指定此属性,则您在视图上指定的任何约束都可能会发生冲突或出现意外行为em>实际上希望使用约束来布局。

我建议您首先考虑一下您实际想要做的是通过AutoLayout约束来指定标签的位置。现在,您实际上想要手动指定一个位置是很少见的,如上所述。

答案 1 :(得分:1)

您想根据屏幕尺寸居中标签吗? 如果是这样,请尝试以下(注意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)
}
相关问题