2017-01-25 56 views
0

我想從標籤初始化按鈕的標題。我有這樣的代碼:用swift快速初始化標籤中的標題按鈕

let smallSquare = CGSize(width: 30, height: 30) 
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare)) 

但是,我不知道我怎麼能和我的標籤初始化標題:

let label = UILabel(frame: CGRectMake(0, 0, 200, 21)) 
label.center = CGPointMake(160, 284) 
label.textAlignment = NSTextAlignment.Center 
label.text = "I'am a test label" 

通常情況下,我使用這個屬性來添加標題用的字符串:

button.setTitle("Button Title",for: .normal)

是否可以簡單地將我的標籤放在我的按鈕標題中?

在此先感謝

+0

可以'addSubView'標籤到按鈕 –

+0

已經然後UIButton的觀點給出titleLable。用它。 – karthikeyan

+0

你試過'button.setTitle(label.text!,for:.normal)'嗎? –

回答

2

您可以添加自定義的子視圖標籤,以您的按鈕像邁克Alter在這樣的(注的註釋中提到:代碼是斯威夫特3,但應該很容易採用斯威夫特2 *提示是代碼中的註釋):

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     view.backgroundColor = .white 

     let smallSquare = CGSize(width: 30, height: 30) 
     let button = UIButton(frame: CGRect(origin: .zero, size: smallSquare)) 
     button.translatesAutoresizingMaskIntoConstraints = false 
     button.backgroundColor = .red 

     // add the button to your view 
     view.addSubview(button) 

     // set constraints of your button 
     button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true 
     button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 


     let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21)) 
     label.translatesAutoresizingMaskIntoConstraints = false 
     label.center = CGPoint(x: 160, y: 284) 
     label.textAlignment = .center 
     label.text = "I'm a test label" 

     // add the label to your button 
     button.addSubview(label) 

     // set constraints of your label 
     label.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true 
     label.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true 
    } 
} 

結果與您的自定義值看起來像這樣(只添加的按鈕的紅色背景,所以你看屁股的框架上相比標籤幀):

enter image description here

0

您的標籤有一個text屬性。你用它來設置一個值,你也可以用它來獲取值。文字是可選的,所以你需要解開。

let labelText = label.text ?? "" 
button.setTitle(labelText, for: .normal) 
0
if let textFromLabel = yourCustomLabel.text { 

    yourButton.setTitle(textFromLabel, .normal) 
} 

是我會建議你做