Swift button created programmatically needs to have 2 lines for title - ios

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)
}

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.

Adding multiple UIButton to multiple UIView in Swift

I have written code below that programmatically creates multiple UIButton that are placed on different UIView. All buttons are similar and different by button title. The code does accomplish what it needs to do, but as you can see, the code is rather verbose, it's too lengthy.
Question
How can I structure the code below and make it compact and succinct?
Code
let myButton0 = UIButton(type: UIButtonType.Custom)
myButton0.setTitle("Text 0", forState:.Normal)
myButton0.titleLabel!.font = UIFont.systemFontOfSize(12)
myButton0.setTitleColor(UIColor.whiteColor(), forState: .Normal)
myButton0.backgroundColor = UIColor.darkGrayColor()
myButton0.frame = CGRectMake(0, 0, 200, 100)
myButton0.alpha = 1
myButton0.showsTouchWhenHighlighted = false
myButton0.adjustsImageWhenHighlighted = false
myButton0.addTarget(self, action: #selector(ViewController.goDoThis0), forControlEvents:.TouchUpInside)
myView0.addSubview(myButton0)
let myButton1 = UIButton(type: UIButtonType.Custom)
myButton1.setTitle("Text 1", forState:.Normal)
myButton1.titleLabel!.font = UIFont.systemFontOfSize(12)
myButton1.setTitleColor(UIColor.whiteColor(), forState: .Normal)
myButton1.backgroundColor = UIColor.darkGrayColor()
myButton1.frame = CGRectMake(0, 0, 200, 100)
myButton1.alpha = 1
myButton1.showsTouchWhenHighlighted = false
myButton1.adjustsImageWhenHighlighted = false
myButton1.addTarget(self, action: #selector(ViewController.goDoThis1), forControlEvents:.TouchUpInside)
myView1.addSubview(myButton1)
let myButton2 = UIButton(type: UIButtonType.Custom)
myButton2.setTitle("Text 2", forState:.Normal)
myButton2.titleLabel!.font = UIFont.systemFontOfSize(12)
myButton2.setTitleColor(UIColor.whiteColor(), forState: .Normal)
myButton2.backgroundColor = UIColor.darkGrayColor()
myButton2.frame = CGRectMake(0, 0, 200, 100)
myButton2.alpha = 1
myButton2.showsTouchWhenHighlighted = false
myButton2.adjustsImageWhenHighlighted = false
myButton2.addTarget(self, action: #selector(ViewController.goDoThis2), forControlEvents:.TouchUpInside)
myView2.addSubview(myButton2)
let myButton3 = UIButton(type: UIButtonType.Custom)
myButton3.setTitle("Text 3", forState:.Normal)
myButton3.titleLabel!.font = UIFont.systemFontOfSize(12)
myButton3.setTitleColor(UIColor.whiteColor(), forState: .Normal)
myButton3.backgroundColor = UIColor.darkGrayColor()
myButton3.frame = CGRectMake(0, 0, 200, 100)
myButton3.alpha = 1
myButton3.showsTouchWhenHighlighted = false
myButton3.adjustsImageWhenHighlighted = false
myButton3.addTarget(self, action: #selector(ViewController.goDoThis3), forControlEvents:.TouchUpInside)
myView3.addSubview(myButton3)
let myButton4 = UIButton(type: UIButtonType.Custom)
myButton4.setTitle("Text 4", forState:.Normal)
myButton4.titleLabel!.font = UIFont.systemFontOfSize(12)
myButton4.setTitleColor(UIColor.whiteColor(), forState: .Normal)
myButton4.backgroundColor = UIColor.darkGrayColor()
myButton4.frame = CGRectMake(0, 0, 200, 100)
myButton4.alpha = 1
myButton4.showsTouchWhenHighlighted = false
myButton4.adjustsImageWhenHighlighted = false
myButton4.addTarget(self, action: #selector(ViewController.goDoThis4), forControlEvents:.TouchUpInside)
myView4.addSubview(myButton4)
(Swift 4.0)
First, write a common method for creating button:
func createButton(title:String,toView:UIView,action:Selector) {
let myButton = UIButton(type: UIButtonType.custom)
myButton.setTitle(title, for:.normal)
myButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
myButton.setTitleColor(UIColor.white, for: .normal)
myButton.backgroundColor = UIColor.darkGray
myButton.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
myButton.alpha = 1
myButton.showsTouchWhenHighlighted = false
myButton.adjustsImageWhenHighlighted = false
myButton.addTarget(self, action: action, for: .touchUpInside)
toView.addSubview(myButton)
}
Then create buttons like this:
let buttonInfos = [
["Text 0",myView0,#selector(ViewController.goDoThis0)],
["Text 1",myView1,#selector(ViewController.goDoThis1)],
["Text 2",myView2,#selector(ViewController.goDoThis2)],
["Text 3",myView3,#selector(ViewController.goDoThis3)],
["Text 4",myView4,#selector(ViewController.goDoThis4)],
]
for buttonInfo in buttonInfos {
self.createButton(title: buttonInfo[0] as! String, toView: buttonInfo[1] as! UIView, action: buttonInfo[2] as! Selector)
}
While this question has already been answered, I would like to contribute another approach adapted from Yun CHEN's answer.
Similarly, create a common method for your buttons:
func createButton(title:String,toView:UIView,action:Selector) {
let myButton = UIButton(type: UIButtonType.custom)
myButton.setTitle(title, for:.normal)
myButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
myButton.setTitleColor(UIColor.white, for: .normal)
myButton.backgroundColor = UIColor.darkGray
myButton.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
myButton.alpha = 1
myButton.showsTouchWhenHighlighted = false
myButton.adjustsImageWhenHighlighted = false
myButton.addTarget(self, action: action, for: .touchUpInside)
toView.addSubview(myButton)
}
Then list out the button information in an array of tuples:
let buttonInfos = [
("Text 0",myView0,#selector(ViewController.goDoThis0)),
("Text 1",myView1,#selector(ViewController.goDoThis1)),
("Text 2",myView2,#selector(ViewController.goDoThis2)),
("Text 3",myView3,#selector(ViewController.goDoThis3)),
("Text 4",myView4,#selector(ViewController.goDoThis4)),
]
And finally create the buttons like so:
for buttonInfo in buttonInfos {
self.createButton(title: buttonInfo.0, toView: buttonInfo.1, action: buttonInfo.2)
}
As you can see in your case, by using tuples, you do not need to cast the types with as! String , as! UIView etc, simplifying and making the code shorter and safer.

Custom UISearchBar

I was curious about how people make their own search interface, I really do not like the standard and decided to write my own. I do not know how to write my own, so I ask to prompt, where you can see all that I know - that's what is needed to create your own UIView.
An example of what I want to do
I once made something similar, if you use swift ,study this code, it will help you, if this is not helpful explain further please.
func addNavigationBar()
{
self.navigationController!.navigationBar.barTintColor = UIColor.blackColor()
let centerView = UIView(frame: CGRectMake(0, 0, 100, 30))
let logo = UIImage(named: "logo.png")
var btnMiddle = UIButton(frame: CGRectMake(0,5,80,20))
btnMiddle.setBackgroundImage(logo, forState: UIControlState.Normal)
btnMiddle.addTarget(self, action: "goBackHome", forControlEvents: UIControlEvents.TouchUpInside)
centerView.addSubview(btnMiddle)
self.navigationItem.titleView = centerView
var buttonDimension = CGFloat(25)
let rightView = UIView(frame: CGRectMake(0, 0, 100, 30))
let leftView = UIView(frame: CGRectMake(0, 0, 100, 30))
let btnr1 = UIButton(frame: CGRectMake(30,0,buttonDimension,buttonDimension))
btnr1.setBackgroundImage(UIImage(named: "_barSearch.png"), forState: UIControlState.Normal)
btnr1.addTarget(self, action: "search", forControlEvents: UIControlEvents.TouchUpInside)
rightView.addSubview(btnr1)
let btnr2 = UIButton(frame: CGRectMake(80,0,buttonDimension,buttonDimension))
btnr2.setBackgroundImage(UIImage(named: "_barSettinges.png"), forState: UIControlState.Normal)
btnr2.addTarget(self, action: "settinges", forControlEvents: UIControlEvents.TouchUpInside)
rightView.addSubview(btnr2)
let btnl3 = UIButton(frame: CGRectMake(0,0,buttonDimension,buttonDimension))
btnl3.setBackgroundImage(UIImage(named: "_barMenu.png"), forState: UIControlState.Normal)
btnl3.addTarget(self, action: "menu", forControlEvents: UIControlEvents.TouchUpInside)
leftView.addSubview(btnl3)
let rightBtn = UIBarButtonItem(customView: rightView)
self.navigationItem.rightBarButtonItem = rightBtn
let leftBtn = UIBarButtonItem(customView: leftView)
self.navigationItem.leftBarButtonItem = leftBtn
}

iOS 9 UIButton Initialization

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 :

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