Add Button to UIView Created Programmatically - ios

I created UIView and Button programmatically
var width = self.view.frame.width - 8
var height = width/8
newView.frame = CGRectMake(4, 39, width, height)
newView.backgroundColor = UIColor.greenColor()
self.view.addSubview(newView)
var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
button.frame = newView.frame
button.backgroundColor = UIColor.whiteColor()
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
button.setTitle(" All Hospitals/Clinics", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
newView.addSubview(button)
I want the button to be inside the UIView, and to have exactly the same location, width and height of UIView
but the result is this
What is wrong with my code ?
Thanks in advance

The issue is caused by this line of code:
button.frame = newView.frame // Equivalent to button.frame = CGRectMake(4, 39, width, height)
In your current implementation the x position of button is 4 and y position is 39, that's why you are getting the result like that way. You need to specify the button frame relative to the newView.
Change the button frame setting code to:
button.frame = CGRectMake(0, 0, width, height)

You should use bounds instead of the frame of the view.
button.frame = newView.bounds
Bounds returns the CGRect of the view coordinates in its own coordinate space, while frame returns the same but in it's parent's coordinate space.
So newView.bounds would return a CGRect like (0,0,width_of_newView,height_of_newview)

your button frame is wrong.
when you declared x and y property of a frame, it is related to its superview.
since you declare your button frame as (4, 39, width, height) it will be placed on coordinate x = 4, y = 39 in view's frame which is exactly like your picture.
if you want to make it like your view, change x and y to 0.

you can use Anchor
lazy var testButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
button.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
button.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
button.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
return button
}()
override func viewDidLoad() {
self.view.addSubview(testButton)
}

Related

Trying to make a UIButton a circle

Im currently trying to make a button into a circle shape and here is my code:
var raffleButton:UIButton = {
var button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 19)
button.setTitle("Tap To Enter Raffle!", for: .normal)
button.setTitleColor(UIColor.red, for: .normal)
button.backgroundColor = .white
button.layer.masksToBounds = true
button.frame = CGRect(x: 1600, y: 160, width: 160, height: 160)
button.layer.cornerRadius = button.frame.width/2
return button
}()
However when I run the code the button is disfigured and looks like the following... round and football like.
Is there any reason why the button looks like it does instead of being a circle?
You have some confusion as to whether you are using autolayout or not.
You have set translatesAutoresizingMaskIntoConstraints to false, but then you are trying to manipulate the frame.
If you add constraints to set the width & height, you will get a result closer to what you are after, but you will still need to adjust your label or font to get it to fit:
var raffleButton:UIButton = {
var button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 19)
button.setTitle("Tap To Enter Raffle!!", for: .normal)
button.setTitleColor(UIColor.red, for: .normal)
button.backgroundColor = .white
button.layer.masksToBounds = true
button.heightAnchor.constraint(equalToConstant: 160).isActive = true
button.widthAnchor.constraint(equalToConstant: 160).isActive = true
button.layer.cornerRadius = 80
return button
}()
Since you set button.translatesAutoresizingMaskIntoConstraints = false, this code won't work button.frame = CGRect(x: 1600, y: 160, width: 160, height: 160). The button's size will be changed during the layout process(won't be (160, 160) anymore). Therefore, it's not a circle.
you can either change button.translatesAutoresizingMaskIntoConstraints = false or try setting button's cornerRadius in viewDidLayoutSubviews method.
your button Height same as button width and then set this code..
anyButton.backgroundColor = .clear
anyButton.layer.cornerRadius = anyButton.frame.height / 2
anyButton.layer.borderWidth = 1
anyButton.layer.borderColor = UIColor.black.cgColor
One semi-obvious thing to note, is if the button frame's height and width is not equal, it will not be a circle :).

When creating a lazy button with a frame, this is created on the upper left corner why this happen?

I create this 'filterButton' and set it to be created on the exact position of the 'menubutton', the 'filterButton' goes directly to the upper left corner of the view.
lazy var filterButton: UIButton! = {
let button = UIButton(frame: CGRect(x: self.menuButton.frame.origin.x, y: self.button.frame.origin.y, width: 45, height: 45))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .blue
button.clipsToBounds = true
return button
}()
and when I check and print the frame of the 'filterButton' it has the value of the 'menuButton', why this is happening?.
Add following constraints where you are adding filterButton to your view
filterButton.leftAnchor.constraint(equalTo: menuButton.leftAnchor).isActive = true
filterButton.topAnchor.constraint(equalTo: menuButton.topAnchor).isActive = true
filterButton.rightAnchor.constraint(equalTo: menuButton.rightAnchor).isActive = true
filterButton.bottomAnchor.constraint(equalTo: menuButton.bottomAnchor).isActive = true
Maybe, when you access to the instance of filterButton, frames of menuButton and button is not correct.
You can use layout constraints or update frame of filterButton in viewDidLayoutSubviews.
the problem is not of lazy button check you menuButton the problem is there for that you can check this :-
lazy var filterButton: UIButton! = {
let button = UIButton(frame: CGRect(x: 200, y: 200, width: 45, height: 45))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .blue
button.clipsToBounds = true
return button
}()

How to make round circle UIButton with different height and width in iOS

Is it possible to set corner radius to make UIButton circle using different height and width of UIButton in Swift.
let button = UIButton(frame: CGRectMake(0, 0, 60, 40))
button.layer.cornerRadius = button.layer.bounds.size.width / 2
button.layer.masksToBounds = true
It won't work because button with different height and width. Please tell me if there is any other approach because button height and width going to be update. I need to make the button always be a circle.
TRY THIS:
let myFirstButton = UIButton()
myFirstButton.setTitle("SUBMIT", forState: .Normal)
myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
myFirstButton.frame = CGRectMake(15, 50, 100, 100)
myFirstButton.layer.cornerRadius = yourButton.bounds.size.width / 2
self.view.addSubview(myFirstButton)
Make a file with name CircularButton
paste the code below class
implement this class on the button on storyboard
Example:
import UIKit
class CircularButton: UIButton {
override func awakeFromNib() {
self.layer.cornerRadius = self.frame.size.width/2
self.clipsToBounds = true
self.layer.borderColor = UIColor.lightGray.cgColor
self.layer.borderWidth = 0.5
}
}

define UIButton programmatically swift

I'm trying to add a button programmatically as follows.
lazy var myButton: UIButton = {
let button = UIButton(type: .System)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.blueColor()
button.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2)
button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
return button
}()
My intention was to create a button with view's width and height, half of view's height. And I also have LeftAnchor, RightAnchor, WidthAnchor, TopAnchor constraints to this button.
I have the following piece of code in my viewDidLoad()
view.addSubview(myButton)
when I try to run this code, I'm not able to see exactly what i want to have on my simulator.
I would like to see button width = view' width and height of button = view height /2
instead I see small button on the left top of the simulator. How do i resolve this issue?
Thanks !
A better bet would be to use AutoLayoutConstraints.
var myButtonHeight: NSLayoutConstraint
view.addSubview(myButton)
myButton.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
myButtonHeight = myButton.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)
myButtonHeight.isActive = true
It's not clear from your comment if changing of the button height is onTouchDown, of if its a toggle as a result of onTouchUpInside, but either way
myButtonHeight.constant = (buttonShouldBeTall) ? 20 : 0
view.setNeedsLayout()
Please keep in mind you'll need to position the leading/trailing/centerX anchor and leading/trailing/centerY anchor as well, depending on where you need it to be

Resizing UIButton height with code?

I am trying to set a clickable "textonly"-button but right now I'm having problem fixing the height for my button. Before all this I tried having it as an label, but then the touchhandling gets complicated so I decided to just do a button with no frame etc..
So now I need to set the buttonheight to the Text thats inside, any ideas?
Heres a code snippet:
//...
button.setTitle("Log in", for: .normal)
button.setTitleColor(.white, for: .normal)
button.layer.borderWidth = 0
button.frame = CGRect
button.addTarget(self, action: #selector(LoginFunction), for: .touchUpInside)
//...
If you want multiple lines of text in your UIButton you should set yourButton.titleLabel?.numberOfLines = 0 and yourButton.titleLabel?.lineBreakMode = .byWordWrapping. You will get multiline button, which height you can configure as you want.
Also you calculate frame of your text you should use
let context = NSStringDrawingContext()
let frame = yourText.boundingRectWithSize(
CGSize(width: yourButtonWidth, height: 9999),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: dictionaryOfYourTextAttributes, context: context)
You should still have a frame for the button to be displayed in the UI. It define yours button position and size (including height). Here is an example for button with position (0,0) and size (100,100):
button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
Maybe what you mean by "frame" is "border". You can achieve borderless button by setting borderWidth to 0, which you already did in your code.
button.layer.borderWidth = 0
If you want to set size for the text you can do:
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)

Resources