简体   繁体   English

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

[英]Swift- How to Display Image over Button?

I'm trying to display an Image over a button, I'm getting BLUE PRINT of Image over button, I have tried so far this- 我正试图在一个按钮上显示一个图像,我正在通过按钮获得图像的蓝色打印,我到目前为止已尝试过 -

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.
}

By above code, I m getting, the following output 通过上面的代码,我得到了以下输出

在此输入图像描述

But the Actual Image is this- 但实际图像是这样的 -

在此输入图像描述

I think your UIButton needs to be of type UIButtonTypeCustom, rather than UIButtonTypeSystem. 我认为您的UIButton需要是UIButtonTypeCustom类型,而不是UIButtonTypeSystem。 You either constructed it as such, or need to update the UIButton's properties in interface builder. 您要么构造它,要么需要在界面构建器中更新UIButton的属性。

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

i think replace this code: 我想替换这段代码:

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){

}

and also add to image in target 并在目标中添加图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM