2017-08-03 112 views
2

我已經閱讀了很多如何更改標籤位置,但我不能這樣做。 這裏是我的簡單的代碼如何更改標籤的位置

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

標籤在故事板中是否有任何限制?如果是,則需要更改它們以移動標籤。 – RomanN

+0

@RomanN我應該刪除它們嗎? –

+0

如果您有它們,只需更新約束的值即可移動標籤: labelLeftConstraint.constant = 50 view.layoutIfNeeded() – RomanN

回答

0

檢查我的工作

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語句,sec ond語句將不會在此處執行

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

    }