Swift - how to display image above button?

I try to display the image above the button, I get BLUE PRINT of Image over button, I already tried 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. } 

In the above code, I get the following output

enter image description here

But the actual image is

enter image description here

+6
source share
2 answers

I think your UIButton should be of type UIButtonTypeCustom, not UIButtonTypeSystem. You either designed it as such, or you must update the UIButton properties in the interface builder.

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

+8
source

I think we will 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){ } 

as well as add to the target image

+3
source

Source: https://habr.com/ru/post/970895/


All Articles