How do I make a circular button? - ios

*I have this answers here : Correct with help of **Yossi
How to put buttons over UITableView which won't scroll with table in iOS***
I know answers work with NavigationControllerController
[self.navigationController.view addSubview:_btnCircle];
I learned to write in Objective C iOS app. Please help me to implement to get the Circle button display on uitableview as shown below. Or help me search keywords.
Example 1:
Example 2:

The simplest way is to add QuartzCore Framework
#import <QuartzCore/QuartzCore.h>
and then use the following code for your button:
button.layer.cornerRadius = 0.5 * button.bounds.size.width;
Now you have the round button from the square one.

In order to make any button round you need to set the cornerRadius property of the button.
Note- In order to make circle you need to make sure that height and width are equal and radius is set half of the width/height. This will make perfect round circle.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(10, 10, 50, 50)];
btn.layer.cornerRadius = 0.5 * btn.bounds.size.width;

For Swift:
button.layer.masksToBounds = true
button.layer.cornerRadius = self.frame.width / 2
If you are creating a custom UIButton (or a custom UIView), implement the following inside the custom class:
override func layoutSubviews() {
super.layoutSubviews()
self.layer.masksToBounds = true
self.layer.cornerRadius = self.frame.width / 2
}

Related

Are these buttons round, or nodular?

Maybe my eyes are deceiving me, but after using this code to create round buttons for a number pad similar to iPhone's Phone app:
for subStack in (mainStackView?.arrangedSubviews)! {
for thisView in (subStack.subviews) {
if let button = thisView as? UIButton {
button.layer.borderWidth = 2
button.layer.borderColor = orangeBorderColor
button.frame.size.width = 76
button.frame.size.height = 76
button.layer.cornerRadius = 0.5 * (button.bounds.size.height)
button.layer.masksToBounds = true
// button.clipsToBounds = true
button.backgroundColor = UIColor.lightGray
button.titleLabel?.font = button.titleLabel?.font.withSize(30)
button.setTitleColor(.black, for: .normal)
}
}
}
I get things that look like this:
I've tried using clipsToBounds, maskToBounds, I've tried the button's .frame and its .bounds property as the basis for the arithmetic, but they still look nodular rather than round to me.
Can someone please offer a suggestion for smoothing them out?
Thanks!
Edit
When I add this:
print(button.frame.size as Any)
print(button.bounds.size as Any)
print(button.layer.cornerRadius as Any)
I get this in the console:
(76.0, 76.0)
(76.0, 76.0)
38.0
You can't directly set the frames of views that are laid out using constraints, and arranged subviews of a stack view must be laid out using constraints. That's your problem. Auto layout is (later) overriding your attempt to set the frame, so your corner radius doesn't match the size of your buttons.
Make a subclass of UIButton. In your subclass, override layoutSubviews to set the button's cornerRadius (and don't forget to call super.layoutSubviews).

Access the UIImageView of the background image of a UIButton

I have a UIButton, and I would like to access the UIImageView of its background image so that I can make the image circular. I know that I can affect the image itself but I would prefer to do this more elegantly. I also know that I can use the button.currentBackgroundImage property to get the UIImage in the background, but I want the view itself. Once I have the view I intend to use this code:
buttonImageView.layer.cornerRadius = buttonImageView.frame.size.width / 2;
buttonImageView.clipsToBounds = YES;
How can I access the buttonImageView?
EDIT:
Due to #vhristoskov's suggestions, I tried cropping the button itself with this code:
self.button.layer.cornerRadius = self.button.frame.size.width/2;
self.button.clipsToBounds = YES;
And it made this shape:
After debugging I found that frame.size.width was 46, when it should have been 100. So I tried this code instead:
self.button.layer.cornerRadius = self.button.currentBackgroundImage.size.width/2;
self.button.clipsToBounds = YES;
And that produced this shape:
And this time, the cornerRadius was being set to 65. So it actually seems like my problem is that I don't have the correct width at the moment. Which property should I access to get the correct number?
Well as I guessed and as you've already found - the problem is in the button size. To be sure that your button's size at runtime is what you expected to be - review your constraints. In the example below the button has vertical and horizontal central alignment and fixed width and height.
Constraints:
To have perfectly circular button you should have button.width == button.height. If this condition is met your code should work like a charm:
self.button.layer.cornerRadius = CGRectGetWidth(self.button.frame) / 2;
self.button.clipsToBounds = YES;
Assuming that you called something like:
[self.myButton setBackgroundImage:[UIImage imageNamed:#"image"] forState:UIControlStateNormal];
in viewDidLoad or earlier, you can then call the following in viewDidAppear:
if (self.myButton.subviews.count > 0 && [self.myButton.subviews[0] isKindOfClass:[UIImageView class]]) {
UIImageView *imageView = self.myButton.subviews[0];
imageView.layer.cornerRadius = imageView.frame.size.width / 2;
imageView.clipsToBounds = YES;
}
but it is not more elegant as the subview ordering is an implementation detail of UIButton and may change at any time.

Set rounded corners globally on UIButtons in iOS application

Is there a way to set UIButtons with rounded corners globally like with color below?
[[UIButton appearance] setBackgroundColor:[UIColor purpleColor]];
The list of properties that you can set using UIAppearance is found here:
What properties can I set via an UIAppearance proxy?
Unfortunately rounded corners are not something that is possible.
You could use something like beautify (https://github.com/beautify/beautify-ios) which enhances the UIKit controls to allow you to specify rounded buttons.
With beautify, the following would give you rounded buttons globally:
BYTheme *theme = [BYTheme new];
theme.buttonStyle.border = [[BYBorder alloc] initWithColor:[UIColor blackColor]
width:2.0f
radius:5.0f];
[[BYThemeManager instance] applyTheme:theme];
I've found this link. Please see if it could help.
Taming UIButton
It is using this
[[basicButton layer] setCornerRadius:18.0f];
As i mentioned in previous answer. You have to subclass UiButton for it.. :)
#import <QuartzCore/QuartzCore.h>
Add this in your header file.
then in implementation,
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100,50);
[btn setTitle:#"Hello" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor colorWithRed:128.0/255.0f green:0.0/255.0f blue:0.0/255.0f alpha:0.7]];
btn.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);//width and height should be same value
btn.clipsToBounds = YES;
btn.layer.cornerRadius = 20;//half of the width
btn.layer.borderColor=[UIColor redColor].CGColor;
btn.layer.borderWidth=2.0f;
cornerRadius will do the trick for you.. Let me know if more info needed.. :)
Edit
This cannot be achieved globally. As you used appearence, here is the list to see what you can customize with UIAppearance. what you can do is you can create a subclass of your UIButton, & there you can write implementation of setCornerRadius in initWithCoder Method.
Migrating advice for a workable solution to Swift (it's also possible using an equivalent ObjC category on UIView):
1. Add this extension https://gist.github.com/d3ce2e216884541217d0
2. Code:
let a = UIButton.appearance()
a.layerCornerRadius = 20.0
a.layerBorderColor = UIColor.redColor().CGColor
a.layerBorderWidth = 2.0
This sort of hack works because of how properties are copied. All appearance changes to things like a.layer and a.titleLabel are not propagated, but extension properties are copied.

custom font on UIbutton title clipped on top of word

I have uploaded a custom font and applied this font on the title of a UIbutton using the following code
videoButton.titleLabel.font = [UIFont fontWithName:#"LaurenScript" size:20];
The problem is that the title is being clipped on the top of the first letter (see photo below). I tried the same font on the UIlabel and it works fine so it is not a problem with the font. I tried also to change the rectFrame using
[videoButton.titleLabel setFrame:CGRectMake(0, 0, 300, 600)];
but that didn't do anything.
Has anybody a clue of how I can fix this problem?
Cheers
I had a similar problem, where a diaeresis got cut off on top of the titlelabel.
I made a UIButton subclass and used this code to fix the problem:
-(void)layoutSubviews
{
[super layoutSubviews];
CGRect frame = self.titleLabel.frame;
frame.size.height = self.bounds.size.height;
frame.origin.y = self.titleEdgeInsets.top;
self.titleLabel.frame = frame;
}
Select button in Interface builder and check for set a vertical alignment panel in the control section Below is example:
Not sure if this is still an issue for anyone, but I found that (with using a custom font) the above solutions did not ultimately fix the issue, especially for a custom UIButton created solely programmatically.
Here is how I managed to fix this issue, with 1 line in particular that resolved the clipping issue:
UIButton *button = [[UIButton alloc] init];
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:#"Nice!" forState:UIControlStateNormal];
[button setFont:[UIFont fontWithName:<CUSTOM FONT NAME> size:buttonWidth/3.0f]];
button = CGRectMake(0, 0, <WIDTH>, <HEIGHT>);
Here was the line that resolved the clipping:
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentFill];
Hopefully this helps anyone else who still were stuck. Happy coding!
had same problem using a button with an image and text with a custom font.
Everything had to be align centered vertically. And image not stretched.
this worked out fine for me.
btn.contentVerticalAlignment = .fill
btn.contentMode = .center
btn.imageView?.contentMode = .scaleAspectFit
I try this in swift 2.1, I adapt this code from Antoine answer. This may not good code but it solve my problem for now. You should make it better for you self.
import UIKit
class CustomUIButton: UIButton {
override func layoutSubviews() {
if var titleFrame : CGRect = titleLabel?.frame{
titleFrame.size = self.bounds.size
titleFrame.origin = CGPointZero
self.titleLabel!.frame = titleFrame
self.titleLabel!.textAlignment = .Center
}
}
}
There is this (sad) solution: https://stackoverflow.com/a/10200908/352628
I have a similar problem. It seems that the titleLabel is just very uncontrollable, and to get control you need to inject a UILabel subview to the button... That makes me sad :(

How to round the corners of a button

I have a rectangle image (jpg) and want to use it to fill the background of a button with rounded corner in xcode.
I wrote the following:
UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
CGRect frame = CGRectMake(x, y, cardWidth, cardHeight);
button.frame = frame;
[button setBackgroundImage:backImage forState:UIControlStateNormal];
However, the button I get with that approach doesn't have its corners rounded: it is instead a plain rectangle that looks exactly like my original image. How can I get instead an image with rounded corner to represent my button?
Thanks!
I tried the following solution with the UITextArea and I expect this will work with UIButton as well.
First of all import this in your .m file -
#import <QuartzCore/QuartzCore.h>
and then in your loadView method add following lines
yourButton.layer.cornerRadius = 10; // this value vary as per your desire
yourButton.clipsToBounds = YES;
You can achieve by this RunTime Attributes
we can make custom button.just see screenshot attached.
kindly pay attention :
in runtime attributes to change color of border follow this instruction
create category class of CALayer
in h file
#property(nonatomic, assign) UIColor* borderIBColor;
in m file:
-(void)setBorderIBColor:(UIColor*)color {
self.borderColor = color.CGColor;
}
-(UIColor*)borderIBColor {
return [UIColor colorWithCGColor:self.borderColor];
}
now onwards to set border color check screenshot
thanks
Pushing to the limits corner radius up to get a circle:
self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;
If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.
You may want to check out my library called DCKit. It's written on the latest version of Swift.
You'd be able to make a rounded corner button/text field from the Interface builder directly:
It also has many other cool features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.
UIButton* closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 90, 35)];
//Customise this button as you wish then
closeBtn.layer.cornerRadius = 10;
closeBtn.layer.masksToBounds = YES;//Important
Import QuartCore framework if it is not there in your existing project, then import #import <QuartzCore/QuartzCore.h> in viewcontroller.m
UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect]];
CGRect frame = CGRectMake(x, y, width, height); // set values as per your requirement
button.layer.cornerRadius = 10;
button.clipsToBounds = YES;
First set width=100 and Height=100 of button
Objective C Solution
YourBtn1.layer.cornerRadius=YourBtn1.Frame.size.width/2;
YourBtn1.layer.borderColor=[uicolor blackColor].CGColor;
YourBtn1.layer.borderWidth=1.0f;
Swift 4 Solution
YourBtn1.layer.cornerRadius = YourBtn1.Frame.size.width/2
YourBtn1.layer.borderColor = UIColor.black.cgColor
YourBtn1.layer.borderWidth = 1.0
Try my code. Here you can set all properties of UIButton like text colour, background colour, corner radius, etc.
extension UIButton {
func btnCorner() {
layer.cornerRadius = 10
clipsToBounds = true
backgroundColor = .blue
}
}
Now call like this
yourBtnName.btnCorner()
For Objective C:
submitButton.layer.cornerRadius = 5;
submitButton.clipsToBounds = YES;
For Swift:
submitButton.layer.cornerRadius = 5
submitButton.clipsToBounds = true
If you want a rounded corner only to one corner or two corners, etc... read this post:
[ObjC] – UIButton with rounded corner - http://goo.gl/kfzvKP
It's a XIB/Storyboard subclass. Import and set borders without write code.
For Swift:
button.layer.cornerRadius = 10.0
updated for Swift 3 :
used below code to make UIButton corner round:
yourButtonOutletName.layer.cornerRadius = 0.3 *
yourButtonOutletName.frame.size.height
Swift 4 Update
I also tried many options still i wasn't able to get my UIButton round cornered.
I added the corner radius code inside the viewDidLayoutSubviews() Solved My issue.
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
anyButton.layer.cornerRadius = anyButton.frame.height / 2
}
Also we can adjust the cornerRadius as follows:
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
anyButton.layer.cornerRadius = 10 //Any suitable number as you prefer can be applied
}
An alternative answer which sets a border too (making it more like a button) is here ... How to set rectangle border for custom type UIButton
For iOS SWift 4
button.layer.cornerRadius = 25;
button.layer.masksToBounds = true;
You can use outlet connection and didSet function for your button on the view;
#IBOutlet weak var button: UIButton!{
didSet {
button.layer.cornerRadius = 5;
button.layer.masksToBounds = true;
}
}

Resources