如何在swift中改变标签的位置

时间:2017-08-03 22:03:40

标签: ios swift position label

我已经阅读了很多如何改变标签的位置,但我不能这样做。 这是我的简单代码

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var TEKST: UILabel!
    @IBOutlet weak var klik: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.green
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func kliksad(_ sender: UIButton) {
        if (view.backgroundColor==UIColor.green){
            TEKST.isHidden = false
            TEKST.text = "Hi"
            view.backgroundColor = UIColor.red
            TEKST.frame.size.width = view.frame.size.width
        } else if(view.backgroundColor == UIColor.red) {
            view.backgroundColor=UIColor.green
            TEKST.textColor=UIColor.purple
            TEKST.text = " Hello "
            TEKST.frame.origin = CGPoint(x: 10, y: 50)
            print(TEKST.frame)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

检查我的工作

1)带约束的标签

enter image description here

enter image description here

2)我的代码

labelToMove.frame.origin = CGPoint(x: 20, y: 20)

[![在此处输入图像说明] [3]] [3]

3)结果

enter image description here

其次 这是你的按钮操作代码

if (view.backgroundColor==UIColor.green){
            TEKST.isHidden = false
            TEKST.text = "Hi"
            view.backgroundColor = UIColor.red
            TEKST.frame.size.width = view.frame.size.width
        } else if(view.backgroundColor == UIColor.red) {
            view.backgroundColor=UIColor.green
            TEKST.textColor=UIColor.purple
            TEKST.text = " Hello "
            TEKST.frame.origin = CGPoint(x: 10, y: 50)
            print(TEKST.frame)
        }

您已将View.color初始化为绿色在didLoad中 然后在行动中你正在检查颜色是否为绿色使其变为红色并使用else if语句,第二个语句将不会在此处执行

   @IBAction func MOveLabell(_ sender: Any) {
        if (view.backgroundColor==UIColor.green){
            view.backgroundColor = UIColor.red
        } 

        if(view.backgroundColor == UIColor.red) {
            view.backgroundColor=UIColor.red
            labelToMove.frame.origin = CGPoint(x: 20, y: 20)
        }

    }