Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift- How to Display Image over Button?

Tags:

swift

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

enter image description here

But the Actual Image is this-

enter image description here

like image 781
ChenSmile Avatar asked Jun 16 '14 12:06

ChenSmile


2 Answers

I think your UIButton needs to be of type UIButtonTypeCustom, rather than UIButtonTypeSystem. You either constructed it as such, or need to update the UIButton's properties in interface builder.

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

like image 75
brindy Avatar answered Nov 11 '22 14:11

brindy


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

like image 35
Ronak Avatar answered Nov 11 '22 14:11

Ronak