Danny B Danny B - 5 years ago 174
Swift Question

Cannot get image to show on UIButton in Swift

I've been working with this for several hours and am diligently attempting to find a solution. I have created a

UIButton
and added a gradient back layer. What I am trying to do is add a
UIImage
to the button. I tried adding the button using the
setImage(image:, forState:)
method. The image appears in the view hierarchy in debugger, but does not appear in the simulator or on my iPad. I also tried adding a custom
UIView
and adding that as a subview to the
UIButton
. I get the same result. Any ideas on how to make the image show on the device or simulator?

deleteKey.frame = CGRect(x: 719, y: 10, width: 134.0, height: 63.0)
deleteKey.backgroundColor = UIColor.clearColor()

altGradients.append(CAGradientLayer())
altGradients[altGradients.count - 1].frame = CGRect(x: 0.0, y: 0.0, width: 134.0, height: 63.0)
altGradients[altGradients.count - 1].startPoint = CGPoint(x: 0.5, y: 0.0)
altGradients[altGradients.count - 1].endPoint = CGPoint(x: 0.5, y: 1.0)
altGradients[altGradients.count - 1].colors = altOffColor
altGradients[altGradients.count - 1].cornerRadius = 5.0

deleteKey.layer.addSublayer(altGradients[altGradients.count - 1])
deleteKey.adjustsImageWhenHighlighted = false
deleteKey.setImage(UIImage(named: "keyboard_delete.png")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
deleteKey.addTarget(self, action: Selector("altKeyPressed:"), forControlEvents: .TouchDown)
deleteKey.addTarget(self, action: Selector("altKeyReleased:"), forControlEvents: .TouchUpInside)
altKeys.append(deleteKey)
self.addSubview(deleteKey)

Answer Source

Lucas, I followed your advice. I created a UIImageView and just added as a subview to the UIButton:

    // Delete key
    deleteKey.frame = CGRect(x: 719, y: 10, width: 134.0, height: 63.0)

    altGradients.append(CAGradientLayer())
    altGradients[altGradients.count - 1].frame = CGRect(x: 0.0, y: 0.0, width: 134.0, height: 63.0)
    altGradients[altGradients.count - 1].startPoint = CGPoint(x: 0.5, y: 0.0)
    altGradients[altGradients.count - 1].endPoint = CGPoint(x: 0.5, y: 1.0)
    altGradients[altGradients.count - 1].colors = altOffColor
    altGradients[altGradients.count - 1].cornerRadius = 5.0

    deleteKey.layer.addSublayer(altGradients[altGradients.count - 1])

    deleteImage.image = UIImage(named: "keyboard_delete.png")
    deleteImage.sizeToFit()
    deleteImage.center = CGPoint(x: deleteKey.frame.width / 2, y: deleteKey.frame.height / 2)

    deleteKey.addSubview(deleteImage)

    deleteKey.backgroundColor = UIColor.clearColor()
    deleteKey.addTarget(self, action: Selector("altKeyPressed:"), forControlEvents: .TouchDown)
    deleteKey.addTarget(self, action: Selector("altKeyReleased:"), forControlEvents: .TouchUpInside)
    altKeys.append(deleteKey)
    self.addSubview(deleteKey)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download