How to set image and text in front of gradientLayer on UIButton? - ios

My code looks like this:
pickerCountry = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
pickerCountry.frame = CGRectMake(self.view.frame.size.width/2 - pickerCountry.frame.size.width, 50, 100, 100)
pickerCountry.center.x = self.view.center.x
pickerCountry.setTitle("Start1", forState: UIControlState.Normal)
pickerCountry.setImage(UIImage(named: "Britain_mdpi.png"), forState: UIControlState.Normal)
pickerCountry.tintColor = UIColor.blackColor()
pickerCountry.titleLabel?.tintColor = UIColor.blackColor()
pickerCountry.layer.cornerRadius = 2
pickerCountry.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 200)
pickerCountry.titleEdgeInsets = UIEdgeInsets(top: 5, left: 50, bottom: 5, right: 5)
pickerCountry.addTarget(self, action: "countryPicker:", forControlEvents: UIControlEvents.TouchUpInside)
ContentView.addSubview(pickerCountry)
and I add gradient in a func like this:
let colorTop = UIColor(netHex:0xffffff).CGColor
let colorBottom = UIColor(netHex:0xebebeb).CGColor
pickerCountryGradientLayer.masksToBounds = true
pickerCountryGradientLayer.cornerRadius = pickerCountry.layer.cornerRadius
pickerCountryGradientLayer.colors = [ colorTop, colorBottom]
pickerCountryGradientLayer.locations = [ 0.0, 1.0]
pickerCountry.layer.insertSublayer(pickerCountryGradientLayer, below: pickerCountry.imageView?.layer)
When I use this last line, insertSublayer like this I see the image, and I sort of see the title, but its color is white, or something, kind of weird. I set the color to black, so if this really does work, how do I change the title color?
I tried using addSublayer, but then I see title label and not the image.

You mention you've set your UIButton's title color but I don't see where you're setting your UIButton's title color. Use:
pickerCountry.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)

Related

UIButton titleLabel text bottom to its frame

How can i display the UIButton titleLabel text to bottom of its frame. Currently i am using the UIEdge top margin and setting the negative UIButton image width, result is not as expected. i also want to place the image center to its frame.
`
let leftButton: UIButton = {
let button = UIButton()
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.ublGray1().cgColor
button.setImage(UIImage.init(named: leftButtonImage)?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = UIColor.cerulean()
button.layer.masksToBounds = false
button.layer.cornerRadius = 37
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(leftButtonTitle, for: .normal)
button.titleEdgeInsets = UIEdgeInsets(top: 110, left: -26, bottom: 0, right: 0)[![enter image description here][1]][1]
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
button.setTitleColor(UIColor.charcoalGrey(), for: .normal)
button.titleLabel?.font = UIFont.aspiraMedium(size: 16)
return button
}()
`
You can try something like this.
How about setting "Title Insets" - bottom - to a negative number? It works.
But if you want it to stick to the bottom of the frame, it won't work, so... how about this:
bt.titleEdgeInsets.top = (bt.imageView?.safeAreaInsets.bottom)!
or bt.titleEdgeInsets.top = (bt.imageView?.alignmentRectInsets.bottom)!

UIButton: superimpose a title on top of an image programmatically

How do I superimpose a button title on top of a button image programmatically and position them both to be dead center in the button frame overlapping each other?
let button = UIButton()
button.setImage(coolpic, for .normal)
button.contentMode = .center
button.setTitle("tap me", for: .normal)
// a bunch of constraints and styling that define the frame
Do I have to set the image as a background image? Do I need to create a UILabel as the button title and add it as a subview of the button?
Thanks!
You can do this with image insets, but I like to use extensions for things like this - that way I can use them anywhere in my app without subclassing. Here's my code for setting an image position in a UIButton:
extension UIButton {
func setImagePosition(at pos:ButtonImagePosition, withAdjustment adj:CGFloat?) {
let _adj:CGFloat = (adj != nil) ? adj! : 0
let width = frame.size.width
var imgWidth = self.imageView?.frame.size.width
switch pos {
case .center:
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
case .right:
imgWidth = imgWidth! - _adj
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: width - imgWidth!, bottom: 0, right: 0)
case .left:
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: width + imgWidth!)
}
}
}
enum ButtonImagePosition {
case left
case right
case center
}
Then I call it as follows
button.setImagePosition(at: .right, withAdjustment: nil)
You could try:
let button = UIButton()
button.setImage(UIImage(named:"yourImage.png")?, for: .normal)
button.setTitle("MyTitle", for: .normal)
button.titleLabel?.font = button.titleLabel?.font.withSize(15)
button.titleLabel?.textAlignment = .center

Resizing a background image on UIButton

I am trying to add a "calendar day" image to surround some text on a clickable UI button like so:
let button = UIButton()
let X_Offset : CGFloat = (95 * CGFloat(buttonCount) ) + 10
let scrollHeight = scrollView.bounds.height
button.frame = CGRect(x: X_Offset, y: scrollHeight/6, width: 70, height: 60)
let buttonText = event.startTime.toShortDayOfWeekString() + "\n" + event.startTime.toShortDayOfMonthString()
button.titleLabel!.lineBreakMode = .byWordWrapping
button.titleLabel!.textAlignment = .center
button.setTitle(buttonText, for: .normal)
button.tag = i
button.backgroundColor = CompanyColor.Red.color
let image = UIImage(named: "calendarDay")
button.setBackgroundImage(image, for: .normal)
button.titleLabel?.font = UIFont(name: "Roboto", size: 14)
button.layer.cornerRadius = 8
button.clipsToBounds = true
But the image is encroaching on the text a bit too much:
How can I get the background image to scale up slightly and leave enough gap for the text?
I think what you what you are looking for is setting imageEdgeInsets for UIButton. Setting of these properties lets you move image around besides its default position. You have to play around to get your desired result.
There are two ways you can do this. One is using Interface Builder and other one is programmatically. Interface builder is easiest way to go I guess. Below image shows how can you set those properties for UIButton.
or try using programmatically like this
button.imageEdgeInsets = UIEdgeInsets(top: -10, left: 32, bottom: -10, right: 50)
You can move title like this
button.titleEdgeInsets = UIEdgeInsets(top: 0, left:0, bottom: 0, right: 20)
Note: Setting UIEdgeInsets like this might have different result if you have dynamic size button e.g. for different screen size. Always make sure that it looks as expected for all screen sizes.

How to resize an image inside an UIButton programmatically?

I have this UIButton and an image to fit in.
I don't want that the image take all the space inside the button but just a little part of it right in the center, but if I resize the button it will resize the image too.
How can I do that, is there an option to set whatever dimension I want independently from the size of the UIButton?
Thanks!
This can be done through code in the following way:
let imageSize:CGSize = CGSize(width: 20, height: 20)
let button:UIButton = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 200, y: 200, width: 60, height: 60)
button.backgroundColor = UIColor.yellow
button.setImage(UIImage(named: "chat.png"), for: UIControl.State.normal)
// The below line will give you what you want
button.imageEdgeInsets = UIEdgeInsets(
top: (button.frame.size.height - imageSize.height) / 2,
left: (button.frame.size.width - imageSize.width) / 2,
bottom: (button.frame.size.height - imageSize.height) / 2,
right: (button.frame.size.width - imageSize.width) / 2)
self.view.addSubview(button)
This way, you can achieve what you wanted.
I couldn't get the button's imageView to resize until I used contentHorizontalAlignment and contentVerticalAlignment both set to .fill. Then using imageEdgeInsets I repositioned the image.
let button = UIButton()
let image = UIImage(systemName: "bag.badge.plus")
button.setImage(image, for: .normal)
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 10, right: 10)
Result:
You can experiment with image view insets. Every UIButton has a property imageView.
In Swift 3 you can do this like so:
//let button = UIButton()
button.imageView?.backgroundColor = UIColor.red
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
red background is just so you know what is changing
I would do it this way:
A UIButton is just a UIView. You can simply add a UIImageView with a set image and call addSubview on the UIButton.
Taking into account what KVISH said before i have implemented this and it worked as expected. I posted this because Houman asked for an example.
//grab the image using the name of the pic
var image = UIImage(named: "picture")
//set the size for the image
image = image?.resize(toWidth: 18)
image = image?.resize(toHeight: 18)
//set the image to the button
buttonName.setImage(image, for: UIControlState.normal)
//adjust the position
buttonName.imageEdgeInsets = UIEdgeInsetsMake(8,16,9,0)
As of iOS 13, when using SF Symbols, I prefer this:
let button = UIButton()
let font = UIFont.systemFont(ofSize: 30) // <- make it larger, smaller, whatever you want.
let config = UIImage.SymbolConfiguration(font: font)
let image = UIImage(systemName: "bag.badge.plus", withConfiguration: config)
button.setImage(image, for: .normal)
These can be achieved by adding imageEdgeInsets to a UIButton.
In swift4.2
button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

add rightview in UIButton

I am trying to display some text and an image over a button. I am using the code from here
let btnSort = UIButton.buttonWithType(UIButtonType.System) as! UIButton
btnSort.frame = CGRectMake(2, 74, 140, 26)
btnSort.tintColor = UIColor.whiteColor()
btnSort.setImage(UIImage(named:"immgg"), forState: UIControlState.Normal)
btnSort.imageEdgeInsets = UIEdgeInsets(top: 6,left: 100,bottom: 6,right: 14)
btnSort.titleEdgeInsets = UIEdgeInsets(top: 0,left: -30,bottom: 0,right: 34)
btnSort.setTitle("SORT", forState: UIControlState.Normal)
btnSort.layer.borderWidth = 1.0
btnSort.layer.borderColor = UIColor.whiteColor().CGColor
btnSort.addTarget(self, action: Selector("showSortTbl"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnSort)
I can see the image at the right place, however the text is not appearing. I think titleEdgeInsets is not working.
the code I tried I got the output what the problem U faced.
btnSort.backgroundColor = UIColor.redColor() --> set the background color and check
let btnSort = UIButton(type: UIButtonType.System) as UIButton! //this is Swift2.0 in this place use your code
btnSort.frame = CGRectMake(2, 74, 140, 40)
btnSort.tintColor = UIColor.whiteColor()
btnSort.setImage(UIImage(named:"youtube16x16.png"), forState: UIControlState.Normal)
btnSort.imageEdgeInsets = UIEdgeInsets(top: 6,left: 100,bottom: 6,right: 14)
btnSort.titleEdgeInsets = UIEdgeInsets(top: 0,left: -30,bottom: 0,right: 34)
btnSort.setTitle("SORT", forState: UIControlState.Normal)
btnSort.layer.borderWidth = 1.0
btnSort.backgroundColor = UIColor.redColor() --> set the background color and check
btnSort.layer.borderColor = UIColor.whiteColor().CGColor
btnSort.addTarget(self, action: Selector("showSortTbl"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnSort)
Swift3
let btnSort = UIButton(type: .system)
btnSort.frame = CGRect(x: 2, y: 74, width: 140, height: 40)
btnSort.tintColor = UIColor.white
btnSort.setImage(UIImage(named:"youtube16x16.png"), for: .normal)
btnSort.imageEdgeInsets = UIEdgeInsets(top: 6,left: 100,bottom: 6,right: 14)
btnSort.titleEdgeInsets = UIEdgeInsets(top: 0,left: -30,bottom: 0,right: 34)
btnSort.setTitle("SORT", for: .normal)
btnSort.layer.borderWidth = 1.0
btnSort.backgroundColor = UIColor.red //--> set the background color and check
btnSort.layer.borderColor = UIColor.white.cgColor
btnSort.addTarget(self, action: #selector(ViewController.showSortTbl), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnSort)
and handle the action as
func showSortTbl() {
// do your stuff here
}
output
Subclass UIButton
Override the layoutSubviews() function
class CustomButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
guard imageView != nil else {
return
}
imageEdgeInsets = UIEdgeInsets(top: 5, left: (bounds.width - 25), bottom: 5, right: 5)
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: imageView!.frame.width)
}
}
Add a button to Storyboard
Add custom class to the button
Change button type to System
Set Title and image to the button
Please check below code.
Hope it will work for you.
let teamImage: UIButton = UIButton(frame: CGRect(x: 0, y: 75, width: 100, height: 50))
let imageTest = UIImage(named: "immgg")
teamImage.setTitle("HypnotoadTitle", forState: .Normal)
teamImage.setBackgroundImage(imageTest, forState: .Normal)
self.view.addSubview(teamImage)
Set only background color and display your text :
let btnSort = UIButton(type: UIButtonType.System) as UIButton // Shift 2.0
btnSort.backgroundColor = UIColor.yellowColor()
OR
btnSort.setTitleColor(UIColor.greenColor(), forState: UIControlState.Normal)

Resources