Swift-如何在按钮上显示图像?

时间:2014-06-16 12:17:47

标签: swift

我正试图在一个按钮上显示一个图像,我正在通过按钮获得图像的蓝色打印,到目前为止我已经尝试了这个 -

override func viewDidLoad()
{
    super.viewDidLoad()

    var birdTexture1 = UIImage(named: "fish.png") as UIImage
    button1.frame = CGRectMake(100, 10, 50, 150)
    button1.setImage(birdTexture1, forState: .Normal)

    button1.setTitle("Testing", forState: UIControlState.Normal)
    button1.addTarget(self, action: "btnAction:", forControlEvents:  UIControlEvents.TouchUpInside)
    self.view.addSubview(button1)

    // Do any additional setup after loading the view, typically from a nib.
}

通过上面的代码,我得到了以下输出

enter image description here

但实际图像是这个 -

enter image description here

2 个答案:

答案 0 :(得分:8)

我认为您的UIButton需要是UIButtonTypeCustom类型,而不是UIButtonTypeSystem。您要么构造它,要么需要在界面构建器中更新UIButton的属性。

更多信息:https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/clm/UIButton/buttonWithType

答案 1 :(得分:3)

我想替换这段代码:

let birdTexture1 = UIImage(named: "fish.png")! as UIImage
let button1:UIButton=UIButton(frame:CGRectMake(100, 50, 50, 150))
button1.setBackgroundImage(birdTexture1, forState: .Normal)
button1.setTitle("Testing", forState: .Normal)
button1.addTarget(self, action: #selector(ViewController.btnActionClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button1)

@IBAction func btnActionClick(sender:AnyObject){

}

并添加到目标

中的图像