以编程方式创建方形获取错误

时间:2016-04-25 08:33:34

标签: ios iphone xcode swift ipad

我正在以编程方式创建一个方块,但是当我运行应用程序时,没有任何显示。

var PB1: UIButton!

    func SetUpButton1() {

    var PB1: UIButton!
    PB1.setBackgroundImage(UIImage(named: "RS"), forState: UIControlState.Normal)
    PB1.center = CGPoint(x: 200, y: 200)
    PB1.bounds = CGRect(x: 0, y: 0, width: 300, height: 50)

    view.addSubview(PB1)

    }

2 个答案:

答案 0 :(得分:0)

两条线都有错误 请设置PB1.frame = CGRectMake(0,0,300,50) 而不是PB1.bounds

答案 1 :(得分:0)

您需要使用UIButton()

初始化PB1对象
  let PB1 = UIButton()
  PB1.bounds = CGRect(x: 0, y: 0, width: 300, height: 50)

  PB1.setBackgroundImage(UIImage(named: "RS"), forState: UIControlState.Normal)
  PB1.center = CGPoint(x: 200, y: 200)

  self.view.addSubview(PB1)

如果要检测按下按钮的时间,则需要调用addTarget(...),它将目标对象和操作方法与控件关联。

PB1.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside)

并在您的类中创建名为buttonPressed的函数。

func buttonPressed(sender: UIButton) {
  // do something here
}
相关问题