add rightview in UIButton - ios

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)

Related

Change UIButton size programmatically in dialog in Swift

I create dialog with custom button UIButton in swift IOS. How can change UIButton size programmatically.
class SuccessMessageView: UIView, UITextFieldDelegate {
private var buttonConfirm : UIButton = {
let button = UIButton()
button.setTitle("Ok", for: .normal)
button.backgroundColor = UIColor(rgb: PreferenceManager.shared.hasDevice() ? purpleColour : orangeColour)
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(confirmFunc), for: .touchDown)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 140.0).isActive = true
button.frame.size.width = 140
return button
}
}
Could you try this? Just remove the frame-related lines.
private lazy var buttonConfirm : UIButton = {
let button = UIButton()
button.setTitle("Ok", for: .normal)
button.backgroundColor = .red
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(confirmFunc), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 200.0).isActive = true
button.heightAnchor.constraint(equalToConstant: 48).isActive = true
return button
}()
fileprivate func Frame() -> CGRect {
var circleFrame = CGRect(x: 0, y: 0, width: 2, height: 2)
return circleFrame
}
I found the solution for set UIButton width and height programatically like that set with constant.
button.anchor(nil, left: nil, bottom: nil, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 20, heightConstant: 30)
button.anchorCenterXToSuperview()

The size of the UIButton doesn't change - Swift

I'm trying to setup the custom navigation bar in my iOS app, but .frame = CGRect(...) doesn't change the size of buttons that I added to it. Buttons appeared inside the navigation bar, but they have wrong size, or maybe constraints, I don't know.
// Setting up the Navigation Bar
private func setupNavigationBar() {
// Remove the shadow under the Navigation Bar
self.navigationController?.navigationBar.shadowImage = UIImage()
let addButton = UIButton(type: .system)
addButton.setImage(UIImage(named: "ic_add")?.withRenderingMode(.alwaysOriginal), for: .normal)
addButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
let settingsButton = UIButton(type: .system)
settingsButton.setImage(UIImage(named: "ic_settings")?.withRenderingMode(.alwaysOriginal), for: .normal)
settingsButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: settingsButton), UIBarButtonItem(customView: addButton)]
}
(I call this function inside the viewDidLoad())
Here you can see the result on my iPhone:
This is work for me. Please try it. (iOS 11)
private func setupNavigationBar() {
// Remove the shadow under the Navigation Bar
self.navigationController?.navigationBar.shadowImage = UIImage()
let addButton = UIButton(type: .custom)
addButton.setImage(UIImage(named: "ic_add")?.withRenderingMode(.alwaysOriginal), for: .normal)
addButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
let settingsButton = UIButton(type: .custom)
settingsButton.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
settingsButton.setImage(UIImage(named: "ic_settings")?.withRenderingMode(.alwaysOriginal), for: .normal)
let menuBarItem = UIBarButtonItem(customView: settingsButton) // new line
let currWidth = menuBarItem.customView?.widthAnchor.constraint(equalToConstant: 10) // new line
currWidth?.isActive = true // new line
let currHeight = menuBarItem.customView?.heightAnchor.constraint(equalToConstant: 10) // new line
currHeight?.isActive = true // new line
navigationItem.rightBarButtonItems = [
menuBarItem, // modify
UIBarButtonItem(customView: addButton)]
}
Try to change the button type
Replace .system to .custom .
Also check the size of original image if it is very large.

Text and Image inside UIButton

I am stuck in UIButton. I want to add to UIButton text and then next to text add an image, like this:
I want to center it.
when I type this:
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Přidat za: \(priceForCategory)", for: .normal)
button.setImage(UIImage(named: "Coin"), for: .normal)
button.imageEdgeInsets = UIEdgeInsets(top: 6, left: -100, bottom: 6, right: 6)
button.titleLabel?.textAlignment = .right
button.alignImageRight()
button.imageView?.contentMode = .scaleAspectFit
button.backgroundColor = UIColor.custom.orange
button.addTarget(self, action: #selector(handleAddCategory), for: .touchUpInside)
button.tintColor = .white
button.titleLabel?.font = UIFont(name: ".SFUIText-Bold", size: 20)
It shows me:
My height breaks and still it doesn't work.
button.alignImageRight()
Means
func alignImageRight() {
if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
semanticContentAttribute = .forceRightToLeft
}
else {
semanticContentAttribute = .forceLeftToRight
}
}
Thanks for every answer.
Create func for adding UIButton
func addRoundedButton() {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Add for: 100", for: .normal)
button.setImage(UIImage(named: "Coin"), for: .normal)
button.alignImageRight()
//Add this line for rounded corner
button.layer.cornerRadius = 20 // set cornerRadius = height/2
button.backgroundColor = UIColor.orange
button.tintColor = .white
button.titleLabel?.font = UIFont(name: ".SFUIText-Bold", size: 20)
view.addSubview(button)
[button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -15),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.heightAnchor.constraint(equalToConstant: 40),
button.widthAnchor.constraint(equalToConstant: 300)].forEach{ $0.isActive = true }
}
Create extension for UIButton (as you already created). but add UIEdgeInsets in extension.
extension UIButton {
func alignImageRight() {
if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
semanticContentAttribute = .forceRightToLeft
imageEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
} else {
semanticContentAttribute = .forceLeftToRight
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15)
}
}
}
Output
TIP
For auto adjust width depend on Text and Image, use this extension

Swift : Programatically Create a UIButton with Some Specific Font And Size

I want to create a basic UIButton programmatically. For example, in my view controller five UIButtons will be created dynamically in the same row and its layout or properties are set for some color, font, and size.
And I also need to add action method for a specific button.
If you wanted to do it programmatically, you might think along the following lines:
Create your buttons in a for... loop in viewDidLoad() (or elsewhere, depending on your requirements):
let buttonWidth : CGFloat = self.view.frame.width / 10
let buttonHeight : CGFloat = 50
for count in 0..<10 {
let newButton = UIButton(frame: CGRect(origin: CGPoint(x: CGFloat(count) * buttonWidth, y: 50), size: CGSize(width: buttonWidth, height: buttonHeight)))
newButton.backgroundColor = UIColor.red
newButton.setTitle("Button #\(count)", for: UIControlState.normal)
newButton.setTitleColor(UIColor.white, for: UIControlState.normal)
newButton.addTarget(self, action: #selector(self.buttonTapped(sender:)), for: UIControlEvents.touchUpInside)
newButton.titleLabel?.font = UIFont(name: "Arial", size: 10)
newButton.tag = count
self.view.addSubview(newButton)
}
Then you can implement the selector buttonTapped(sender: UIButton) as follows, retrieving the button's tag so you can tailor the action (via a switch statement, for example):
func buttonTapped(sender: UIButton) -> Void {
print("\(sender.tag) was tapped!")
// Do something more interesting based on the tag here...
}
This allows you to set up a lot of button actions without a lot of different selectors. Hope that helps.
Create uibuttons and add them inside main view see example below.
class yourClassName: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// here method CGRectMake defines x, y, width, height
var btnOne = UIButton(frame: CGRectMake(0, 0, 50, 50))
var btnOne = UIButton(frame: CGRectMake(0, 0, 50, 50))
self.view.addSubview(btnOne) // add button inside view
self.view.addSubview(btnOne) // add button inside view
// using selector you must specify a method for each button
btnOne.addTarget(self, action: #selector(self.actionOne), forControlEvents: .TouchUpInside)
btnTwo.addTarget(self, action: #selector(self.actionTwo), forControlEvents: .TouchUpInside)
}
Actions methods:
func actionOne(sender : UIButton) {
print("button one tapped")
}
func actionTwo(sender : UIButton) {
print("button second tapped")
}
let bacViewOne=UIButton(frame: CGRectMake(20, 60 , 130, 130))
bacViewOne.backgroundColor=UIColor.whiteColor()
bacViewOne.layer.cornerRadius=5.0
btn1 = UIButton(type: UIButtonType.Custom) as UIButton
btn1.setImage(UIImage(named: "new.png"), forState: UIControlState.Normal)
btn1.frame = CGRectMake((bacViewOne.frame.size.width-90)/2, 5 , 90, 90)
//btn1.backgroundColor = UIColor.whiteColor()
btn1.tag = 1
btn1.addTarget(self, action: #selector(ViewController.dashboard(_:)), forControlEvents: UIControlEvents.TouchUpInside)
bacViewOne.addSubview(btn1)
self.view.addSubview(bacViewOne)
let l1 = UILabel(frame: CGRectMake((bacViewOne.frame.size.width-90)/2, 100, 90, 21))
l1.textAlignment = NSTextAlignment.Center
l1.textColor = UIColor(red: 41/255.0, green: 43/255.0, blue: 64/255.0, alpha: 1)
l1.text = "Dashboard"
//l1.font = UIFont (name: "BakerSignetBT-Roman", size: 15)
bacViewOne.addSubview(l1)
l1.font = UIFont.systemFontOfSize(11)
var bacViewT=UIButton(type: UIButtonType.Custom) as UIButton
bacViewT .frame = CGRectMake(20, 240, 130, 130)
bacViewT.backgroundColor=UIColor.whiteColor()
bacViewT.layer.cornerRadius=5.0
btn3 = UIButton(type: UIButtonType.Custom) as UIButton
btn3.setImage(UIImage(named: "Usernew.png"), forState: UIControlState.Normal)
btn3.frame = CGRectMake((bacViewT.frame.size.width-90)/2, 5, 90, 90)
// btn3.backgroundColor = UIColor(red: 41/255.0, green: 43/255.0, blue: 64/255.0, alpha: 1)
btn3.tag = 2
btn3.addTarget(self, action: #selector(ViewController.userExpenses(_:)), forControlEvents: UIControlEvents.TouchUpInside)
bacViewT.addSubview(btn3)
self.view.addSubview(bacViewT)
let l2 = UILabel(frame: CGRectMake((bacViewT.frame.size.width-100)/2, 100, 100, 21))
l2.textAlignment = NSTextAlignment.Center
l2.textColor = UIColor(red: 41/255.0, green: 43/255.0, blue: 64/255.0, alpha: 1)
l2.text = "User Expense"
//l2.font = UIFont (name: "BakerSignetBT-Roman", size: 15)
bacViewT.addSubview(l2)
l2.font = UIFont.systemFontOfSize(11)
//7
let bacViewTh=UIButton(frame: CGRectMake(170, 60, 130, 130))
bacViewTh.backgroundColor=UIColor.whiteColor()
bacViewTh.layer.cornerRadius=5.0
btn7 = UIButton(type: UIButtonType.Custom) as UIButton
btn7.setImage(UIImage(named: "events.png"), forState: UIControlState.Normal)
btn7.frame = CGRectMake((bacViewTh.frame.size.width-90)/2, 5, 90, 90)
btn7.tag = 3
btn7.addTarget(self, action: #selector(ViewController.upcomingEvents(_:)), forControlEvents: UIControlEvents.TouchUpInside)
bacViewTh.addSubview(btn7)
let l3 = UILabel(frame: CGRectMake((bacViewTh.frame.size.width-100)/2, 100, 100, 21))
l3.textAlignment = NSTextAlignment.Center
l3.textColor = UIColor(red: 41/255.0, green: 43/255.0, blue: 64/255.0, alpha: 1)
l3.text = "Upcoming Events"
//l3.font = UIFont (name: "BakerSignetBT-Roman", size: 15)
bacViewTh.addSubview(l3)
l3.font = UIFont.systemFontOfSize(11)
self.view.addSubview(bacViewTh)
//8
let bacViewF=UIButton(frame: CGRectMake(170, 240, 130, 130))
bacViewF.backgroundColor=UIColor.whiteColor()
bacViewF.layer.cornerRadius=5.0
btn9 = UIButton(type: UIButtonType.Custom) as UIButton
btn9.setImage(UIImage(named: "Location.png"), forState: UIControlState.Normal)
btn9.frame = CGRectMake((bacViewF.frame.size.width-90)/2, 5, 90, 90)
btn9.tag = 4
btn9.addTarget(self, action: #selector(ViewController.userLocations(_:)), forControlEvents: UIControlEvents.TouchUpInside)
bacViewF.addSubview(btn9)
self.view.addSubview(bacViewF)
let l4 = UILabel(frame: CGRectMake((bacViewF.frame.size.width-100)/2, 100, 100, 21))
l4.textAlignment = NSTextAlignment.Center
l4.textColor = UIColor(red: 41/255.0, green: 43/255.0, blue: 64/255.0, alpha: 1)
l4.text = "User Locations"
bacViewF.addSubview(l4)
l4.font = UIFont.systemFontOfSize(11)

Set button type

I am creating a button programatically and I would like to know how to set that button's UIButtonType.
This is how I am creating my button:
let headerPlusButon:UIButton = UIButton(frame: CGRectMake(5, tableView.frame.width - 30, 20, 20))
headerPlusButon.addTarget(self, action: "paymentAddButtonTapped", forControlEvents:.TouchUpInside)
There is no "setButtonTypeFor..." method like how you would change the title's text and obviously this doesn't work:
headerPlusButon.buttonType = UIButtonType.ContactAdd
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender:UIButton!)
{
println("Button tapped")
}
from swift 2 replace UIButton declaration with below line.
let button = UIButton(type: .System) as UIButton
Here is my code
let tutorialButton = UIButton.init(type: .infoDark)
tutorialButton.frame = CGRect(x: self.view.frame.size.width - 20, y: 42, width: 20, height: 20)
tutorialButton.addTarget(self, action: #selector(self.showTutorial), for: .touchUpInside)
view.addSubview(tutorialButton)
I hope it can help you!

Resources