第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何以編程方式創(chuàng)建按鈕?

如何以編程方式創(chuàng)建按鈕?

小怪獸愛吃肉 2019-08-30 11:09:35
如何UIButton在Swift中以編程方式創(chuàng)建圖形元素(如a )?我試圖在視圖中創(chuàng)建并添加按鈕,但無法進(jìn)行。
查看完整描述

3 回答

?
Helenr

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊

以下是UIButton使用targetAction以編程方式添加的完整解決方案。

Swift 2.2


override func viewDidLoad() {

  super.viewDidLoad()


  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

  button.backgroundColor = .greenColor()

  button.setTitle("Test Button", forState: .Normal)

  button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)


  self.view.addSubview(button)

}


func buttonAction(sender: UIButton!) {

  print("Button tapped")

}

使用NSLayoutConstraint而不是frame為每個(gè)iPhone屏幕正確放置按鈕可能更好。


更新了Swift 3.1的代碼:


override func viewDidLoad() {

  super.viewDidLoad()


  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

  button.backgroundColor = .green

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

  button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)


  self.view.addSubview(button)

}


func buttonAction(sender: UIButton!) {

  print("Button tapped")

}

更新了Swift 4.2的代碼:


override func viewDidLoad() {

  super.viewDidLoad()


  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

  button.backgroundColor = .green

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

  button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)


  self.view.addSubview(button)

}


@objc func buttonAction(sender: UIButton!) {

  print("Button tapped")

}

如果func buttonAction聲明private或上述仍然有效internal。


查看完整回答
反對(duì) 回復(fù) 2019-08-30
  • 3 回答
  • 0 關(guān)注
  • 458 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)