iOS 9 UIButton Initialization - ios

I am trying to initialize a UIButton programmatically but see one of these errors:
buttonWithType is unavailable: use object construction UIButton(type:)
or
error: incorrect argument label in call (have 'buttonWithType:', expected 'type:')
for char in keys {
let btn: UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
btn.frame = CGRectMake(0, 0, 20, 20)
btn.setTitle(char, forState: .Normal)
btn.sizeToFit()
btn.titleLabel?.font = UIFont.systemFontOfSize(20)
btn.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.1, brightness: 0.81, alpha: 1)//
btn.setTitleColor(UIColor(white: 1.0, alpha: 1.0), forState: .Normal)
btn.setContentHuggingPriority(1000, forAxis: .Horizontal)
btn.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
btn.addTarget(self, action: Selector("handleBtnPress:"), forControlEvents: .TouchUpInside)
self.addSubview(btn)
}

The convenience initializer for UIButton has changed.
convenience init(type buttonType: UIButtonType)
Swift 3:
let btn = UIButton(type: .system) // note the lower case s
Swift 2.x:
let btn = UIButton(type: .System)

iOS 10 Xcode 8.....
let button = UIButton(type: .system) // note the lower case s
button.setTitle("Dismiss", for: UIControlState())
button.backgroundColor = UIColor.white
let buttonWidth: CGFloat = alertWidth/2
let buttonHeight: CGFloat = 40
button.frame = CGRect(x: alertView.center.x - buttonWidth/2, y: alertView.center.y - buttonHeight/2, width: buttonWidth, height: buttonHeight)
button.addTarget(self, action: #selector(ExampleIIIViewController.dismissAlert), for: UIControlEvents.touchUpInside)
alertView.addSubview(button)

In iOS 9 convenience init has been changed for buttonWithType. You cannot use
let button = UIButton.buttonWithType(UIButtonType.System)
instead use
let button = UIButton(type: UIButtonType.System)
Below is syntax :

Related

Set image and title both on RightBarButton

I want to set image and title both on rightBarButton. Title will come first. I searched a lot but all the articles are related to leftBarButton. So can anyone please tell me, how to set both of them?
func methodForSettingButtonClicked() {
let buttonSetting = UIButton(type: .custom)
buttonSetting.frame = CGRect(x: 0, y: 5, width: 25, height: 25)
let imageReg = UIImage(named: "setting")
buttonSetting.setTitle("Settings", for: .normal)
buttonSetting.setImage(imageReg, for: .normal)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = buttonSetting
self.navigationItem.rightBarButtonItem = leftBarButton;
}
try barbutton item with custom VIew as follows:-
let button = UIButton(type: .Custom)
button.setImage(UIImage(named: "icon_right"), forState: .Normal)
button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
button.frame = CGRectMake(0, 0, 53, 31)
button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
let label = UILabel(frame: CGRectMake(3, 5, 50, 20))
label.font = UIFont(name: "Arial-BoldMT", size: 16)
label.text = "title"
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.backgroundColor = UIColor.clearColor()
button.addSubview(label)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
imageEdgeInsets plays a important role.
Try it as below and set title as you want
let button = UIButton(type: .system)
button.setImage(UIImage(named: "icon_image_name"), for: .normal)
button.setTitle("Categories", for: .normal)
button.addTarget(self, action: #selector(clickOnButtonActionMethod), for: .touchUpInside)
button.sizeToFit()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
If you want then change button property as you want.
You can do like this way,
let button = UIButton(type: .custom)
button.setTitle("Settings", for: .normal)
button.setImage(#imageLiteral(resourceName: "settings"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.setTitleColor(UIColor.white, for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
It works for me, hope it can help you.

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)

Swift button created programmatically needs to have 2 lines for title

I am creating buttons programmatically like this:
let stage: Stages = stagesObjectsArray[i]
let button = UIButton(type: .Custom) as UIButton
button.setTitle(stage.name, forState: .Normal)
button.sizeToFit()
button.frame.origin = buttonPosition
let buttonIncrement = button.frame.size.width + padding.width
buttonPosition.x = buttonPosition.x + buttonIncrement
button.backgroundColor = UIColor.blackColor()
button.titleLabel?.font = UIFont(name: "", size: widthOfScreen/3.2)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
button.tag = stage.id
button.addTarget(self, action: #selector(GamesAllViewController.buttonPressedTopMenu(_:)), forControlEvents: .TouchUpInside)
buttonView.addSubview(button)
What I want to implement and can't figure out how is to have the title of the button on 2 rows if the width of the button becomes too big(for instance more than half the width of the screen).
I have found some questions on this topic, but they all assume they know the title of the button, while in my case it is dynamic and I do not know what it might be.
I have tried this code, but with no change:
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 2
Can somebody help?
You can use "\n" and NoOFLines to 0
try this code
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
let button = UIButton(type: .Custom) as UIButton
button.setTitle("Line 1\nLine 2", forState: .Normal)
button.sizeToFit()
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 0
button.titleLabel!.textAlignment = NSTextAlignment.Center
button.frame = CGRectMake(20, 100, 280, 40)
button.titleLabel?.textColor = UIColor.redColor()
button.backgroundColor = UIColor.blackColor()
button.addTarget(self, action: "methodName:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}

UIButton does not have a member named setTranslatesAutoresizingMaskIntoConstraints

I am using xcode 7 beta 2 and getting the following error. How can I solve it?
UIButton does not have a member named setTranslatesAutoresizingMaskIntoConstraints
for char in keys {
let btn = UIButton(type: UIButtonType.System) as UIButton
btn.frame = CGRectMake(0, 0, 20, 20)
btn.setTitle(char, forState: .Normal)
btn.sizeToFit()
btn.titleLabel?.font = UIFont.systemFontOfSize(20)
btn.setTranslatesAutoresizingMaskIntoConstraints(false)
btn.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.1, brightness: 0.81, alpha: 1)//
btn.setTitleColor(UIColor(white: 1.0, alpha: 1.0), forState: .Normal)
btn.setContentHuggingPriority(1000, forAxis: .Horizontal)
btn.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
btn.addTarget(self, action: Selector("handleBtnPress:"), forControlEvents: .TouchUpInside)
self.addSubview(btn)
}
translatesAutoresizingMaskIntoConstraints is a (boolean) property
of UIView. In Objective-C, you can use the "dot syntax" or the
setter method to assign a value to the property
btn.translatesAutoresizingMaskIntoConstraints = NO;
[btn setTranslatesAutoresizingMaskIntoConstraints:NO];
but in Swift you just assign a new value to the property:
btn.translatesAutoresizingMaskIntoConstraints = false

Cannot change textColor and font size inside the loop in swift

I have no idea why the font size and text Color doesn't takes any effect in the loop...anyone help??
Here is my code:
var buttons = ["N","F","S","D","C","A","R"]
for button in buttons
{
var Button:UIButton = UIButton()
Button = UIButton(frame: CGRect(x:10, y: 20, width: 80, height: 80))
Button.frame.origin = ButtonPosition
ButtonPosition.x = ButtonPosition.x + buttonIncrement
Button.layer.cornerRadius = 3
Button.clipsToBounds = true
Button.backgroundColor = UIColor.groupTableViewBackgroundColor()
Button.setTitle("\(button)", forState: UIControlState.Normal)
Button.titleLabel?.text = "\(button)"
Button.titleLabel?.font = UIFont(name:"Chalkboard SE Regular", size: 30)
Button.titleLabel?.textColor = UIColor.blackColor()
Button.setBackgroundImage(UIImage.imageWithColor(UIColor.colorWithHex("#b8b4af", alpha: 0.5)), forState: .Highlighted)
Button.addTarget(self, action: "check:", forControlEvents: UIControlEvents.TouchUpInside)
buttonView.addSubview(Button)
}
return buttonView
First remove the line Button.titleLabel?.text = "\(button)".
This one is enough Button.setTitle("\(button)", forState: UIControlState.Normal).
Then you should use setTitleColor method from a button to change it.
Button.setTitleColor(UIColor. blackColor(), forState: UIControlState.Normal)
Finally you made a mistake in the name of your font :
Button.titleLabel?.font = UIFont(name:"ChalkboardSE-Regular", size: 30.0)
That's it!
You should edit directly the button, not the titleLabel, like this:
Button.setTitle("\(button)", forState: .Normal)
Button.setTitleColor(UIColor.blackColor(), forState: .Normal)

Resources