How to scale image and center it on a UIButton in Swift? - swift

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)
I have an image that I've set on my button, but I'd like to scale it to be smaller than the button (for example the image should be 50,50) and center in the button. How might I do this in Swift?

Xcode 8.3.1 • Swift 3.1
let button = UIButton(type: .custom)
let image = UIImage(named: "myimage.png")
func buttonTouchDown(_ button: UIButton) {
print("button Touch Down")
}
override func viewDidLoad() {
super.viewDidLoad()
button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100)
button.backgroundColor = .clear
button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
button.setTitle("Title", for: .normal)
button.setTitleColor(.black, for: .normal)
button.setImage(image, for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
view.addSubview(button)
}

Swift 5, Swift 4, Swift 3
var image = UIImage(named: "myimage") as UIImage!
btnetc.setImage(image, for: .normal)
btnetc.imageView?.contentMode = .scaleAspectFill
or
btnetc.imageView?.contentMode = .scaleAspectFit
or
btnetc.imageView?.contentMode = .scaleToFill

Ther is a much easier way to do this where you don't have to deal with content insets. Here its is:
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)
button.contentMode = .center
button.imageView?.contentMode = .scaleAspectFit

Or via XIB after selecting your UIButton.
Just make sure your insets are all the same.

Xcode 13, Swift 5
Using storyboard, select the button, then in the size inspect click the dropdown on size just above Content inset. There is a list of sizes to select from, and this will adjust your image size(if you use system image). The default size is already set when you added the button on the storyboard to the View Controller.

Related

Text color for uilabel not setting

I creating UIButton like that:
okBtn = UIButton()
okBtn.setTitle("OK", for: .normal)
okBtn.setTitle("OK", for: .selected)
okBtn.titleLabel?.textColor = .purpleLight
okBtn.backgroundColor = .red
okBtn.addTarget(self, action: #selector(didTapOKBtn), for: .touchUpInside)
self.addSubview(okBtn)
However, color is not setted, i added a screen to show how it looks.
Use title color
okBtn.setTitleColor(UIColor.blue, for: UIControlState.normal)
Use frame as required & add to your view as -
override func viewDidLoad() {
super.viewDidLoad()
let okBtn = UIButton(frame: CGRect(x: 20, y: 70, width: 50, height: 50))
okBtn.setTitle("OK", for: .normal)
okBtn.backgroundColor = .red
okBtn.setTitleColor(.white, for: .normal)
view.addSubview(okBtn)
}
Set the frame size first.
okBtn = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) //Sets the frame size on your viewController
okBtn.setTitle("OK", for: .normal)
okBtn.setTitleColor(UIColor.purple, for: .normal) //Sets the color of the text on the button
//There is no color as purpleLight. You need to set the rgb to get your desired color.
okBtn.backgroundColor = .red
okBtn.addTarget(self, action: #selector(didTapOKBtn), for: .touchUpInside)
self.view.addSubview(okBtn)

Removing a UILabel programmatically after a button is pressed

I am trying to create/show a label when a button is pressed, and then delete/hide the same label when the same button is pressed again. I am trying to do this all programmatically in Swift.
I have tried using label.removeFromSuperview() but it doesn't seem to have any effect. However when i try removing the button in the same code location using button.removeFromSuperview()
var label = UILabel()
let labelImage = UIImage(named: "Strike Line.png")
/* to select checkmarked state */
func pressCheck() {
let image = UIImage(named: "Checkmark.png")
button.setBackgroundImage(image, for: UIControlState.normal)
button.addTarget(self, action:#selector(self.pressUnCheck), for: .touchUpInside)
self.view.addSubview(button)
textField1.textColor = UIColor.gray //change textfield to a gray color
label = UILabel(frame: CGRect(x : 31, y : 69, width: 200, height: 2))
label.backgroundColor = UIColor(patternImage: labelImage!)
self.view.addSubview(label)
}
func pressUnCheck()
{
let image = UIImage(named: "To Be Completed Circle.png")
button.setBackgroundImage(image, for: UIControlState.normal)
button.addTarget(self, action:#selector(self.pressCheck), for: .touchUpInside)
self.view.addSubview(button)
label.removeFromSuperview()
textField1.textColor = UIColor.black
}
Here is where i am trying to remove/hide the label.
Since this apparently was the fix I'll drop it in as an answer.
Add button.removeTarget(nil, action: nil, for: .allEvents) before you add any new targets to your button.
If you don't remove the current target it'll have multiple targets and be calling both pressCheck() and pressUnCheck() on each button press.
There's a few ways to handle this... If you just want to hide it you can use
label.isHidden = true - would hide the label.
label.isHidden = false - would show the label.

tvOS Button Action

I create a UIButton in tvOS via Swift
let randomBtn = UIButton()
randomBtn.setTitle("Zufällig", forState: .Normal)
let RndNormal = UIImage(named: "RndNormal")
let RndHoover = UIImage(named: "RndHoover")
randomBtn.setImage(RndNormal, forState: .Normal)
randomBtn.setImage(RndHoover, forState: .Focused)
randomBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
randomBtn.setTitleColor(UIColor.whiteColor(), forState: .Focused)
randomBtn.addTarget(self, action: #selector(ViewController.click(_:)), forControlEvents: UIControlEvents.TouchUpInside)
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
randomBtn.frame = CGRect(x: screenWidth - 150, y: 60 , width: 70 , height: 70)
self.view.addSubview(randomBtn)
But the action never get fired if I press the button, is there anything different in tvOS?
func click(sender: UIButton) {
print("click")
}
In tvOS for Button action UIControlEvents TouchUpInside will not call.
You have to use UIControlEvents PrimaryActionTriggered like below.
randomBtn.addTarget(self, action: #selector(ViewController.click(_:)), forControlEvents: UIControlEvents. PrimaryActionTriggered)
Also Refer this link if you have any confusion
https://forums.developer.apple.com/thread/17925
randomBtn.addTarget(self, action: #selector(ViewController.click(_:)), forControlEvents: UIControlEvents.PrimaryActionTriggered)
Solved it, its just a other UIControlEvents

UIButton background color overlaps text on highlight

After I set my UIButton's backgroundColor and textColor for state highlighted the following output is presented:
The problem here is that the button's background overlaps the white text. How can I solve this?
I also have lots of problem on tvOS with setting the background and text color from the Interface Builder (not working from State Config). I have to make a combination of the IB's properties and code.
Here is my code:
if shopNowButton.highlighted == true {
shopNowButton.highlighted = false
shopNowButton.backgroundColor = UIColor.orangeColor()
shopNowButton.setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
}
else {
shopNowButton.highlighted = true
shopNowButton.backgroundColor = UIColor.whiteColor()
shopNowButton.layer.borderWidth = 1
shopNowButton.layer.borderColor = UIColor.orangeColor().CGColor
shopNowButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
}
This may help.
Change the Button-Type: System to Custom (IB or programmatically),
Follow image
changes behaviour of highlighted button.
Add this property in your method "adjustsImageWhenHighlighted = NO".
I believe the UIControlState you're actually looking for is Focused rather than Highlighted.
Here's an example of how to change the backgroundColor and titleColor of a UIButton when it becomes focused. (Accomplished with the help of this answer):
import UIKit
class ViewController: UIViewController {
let myButton = UIButton(type: UIButtonType.Custom)
let myOtherButton = UIButton(type: UIButtonType.Custom)
override func viewDidLoad() {
super.viewDidLoad()
// Button we will change on focus
myButton.frame = CGRectMake(view.frame.midX - 300, view.frame.midY, 400, 100)
myButton.setTitle("myButton", forState: .Normal)
// Normal
myButton.backgroundColor = UIColor.whiteColor()
myButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
// Focused
myButton.setBackgroundImage(imageWithColor(UIColor.orangeColor()), forState: .Focused)
myButton.setTitleColor(UIColor.whiteColor(), forState: .Focused)
view.addSubview(myButton)
// Other button so we can change focus // Just for example
myOtherButton.frame = CGRectMake(view.frame.midX + 300, view.frame.midY, 400, 100)
myOtherButton.setTitle("myOtherButton", forState: .Normal)
// Normal
myOtherButton.backgroundColor = UIColor.whiteColor()
myOtherButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
// Focused
myOtherButton.setBackgroundImage(imageWithColor(UIColor.orangeColor()), forState: .Focused)
myOtherButton.setTitleColor(UIColor.whiteColor(), forState: .Focused)
view.addSubview(myOtherButton)
}
// Function to create a UIImage filled with a UIColor
func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
This example in action:

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