custom font on UIbutton title clipped on top of word - ios

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 :(

Related

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.

Still no solution for my uibutton position [duplicate]

I am under one project.In that I created one uibutton at bottom of my viewcontroller using code (Not via storyboard).But when i run my app,my uibutton are placing in differents positions.for example in iphone 5,6 simulator are in some position.In 4s,ipad simulator my uibutton is unvisible.Also i check with my own device(iphone 6) ,in that also my uibutton is not able to see.
Needed
I used below code for creating & placing my button position.but its not fit in one position.
CGFloat buttonSize = 40;
UIButton * disButton = [[UIButton alloc] init];
disButton.backgroundColor = [UIColor redColor];
UIImage *btnImage = [UIImage imageNamed:#"23"];
[disButton setImage:btnImage forState:UIControlStateNormal];
disButton.frame = CGRectMake(150, 523, 40, 40);
[overlayView addSubview:disButton];
[disButton addTarget:self action:#selector(dismissPopUpViewController)
forControlEvents:UIControlEventTouchUpInside];
In my code i use to place position in this line:
disButton.frame = CGRectMake(150, 523, 40, 40);
=> x-position = 150
=> Y-position = 523
Kindly please give some code solution for this problem.
As per all comments about your question.You need to set constraint for your UIButon.Use only centre x,centre y because that will helpfull to see your layout in all devices. And there is a already solution for your problem.see these below links for setting auto layout for UIButton
Link 1
Link 2
Link 3
Sure this will help you !

Text Alignment issue when I set the custom font

When I set the custom font for the segmented control then it changes the vertical text alignment. I am using below code to set the font .
// I dont think these lines are creating any issue but just wanted to paste all the code
self.segmentType.layer.borderColor = navigationTintColor.CGColor;
self.segmentType.layer.cornerRadius = 0.0;
self.segmentType.layer.borderWidth = 1.5;
// These are the lines that are changing the text alignment
UIFont *font = [UIFont fontWithName:ftHelveticaNeueLTPro_Th size:13.5];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:UITextAttributeFont];
[self.segmentType setTitleTextAttributes:attributes
forState:UIControlStateNormal];
Here is the screenshot of whats is happening . If you observer, the text is not vertically centre aligned .
Please help me . Thank you in advance !!
The below code suggested by #Emmanuel works perfectly fine. You can change the vertical offset to align the text vertically at the center .
[self.segmentType setContentPositionAdjustment:UIOffsetMake(0, 2) forSegmentType:UISegmentedControlSegmentAny barMetrics:UIBarMetricsDefault];
Can you please try it using custom UILabel on custom view on it. Change & modify frame value of either titleLabel or customSegmentView as per convenience on actual view. And add this whole view as subview on your segmented control.
UIView *customSegmentView = [[UIView alloc] init];
UILabel *segmentTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 7.0f,180.0f,22.6f)];
segmentTitleLabel.text = #"your-text";
segmentTitleLabel.backgroundColor = [UIColor clearColor];
segmentTitleLabel.textAlignment = UITextAlignmentCenter;
segmentTitleLabel.font = [UIFont fontWithName:#"ftHelveticaNeueLTPro_Th" size:13.5f];
customSegmentView.frame = CGRectMake(60, 20, 180, 35);
[customSegmentView addSubview:segmentTitleLabel];
[self.segmentType setTitleView:customSegmentView];
Hope that will work for your issue. Please check and let me know if we have to go with another solution.
In InterfaceBuilder on XCode 6 there is a Content Offset control for the segments, which affects the baseline of the text. I had this problem because my Content Offset was 2 in the Y dimension instead of 0.

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.

UIButton doesn't listen to content mode setting?

firstButton is a UIButton of type Custom. I'm programmatically putting three of them across each cell of a table, thusly:
[firstButton setImage:markImage forState:UIControlStateNormal];
[firstButton setContentMode:UIViewContentModeScaleAspectFit];
[cell.contentView addSubview:firstButton];
Elsewhere, I'm telling it to clipToBounds. What I get is a crop of the center square of the image, rather than an aspect-scaled rendering of it. I've tried this lots of ways, including setting the mode property on firstButton.imageView, which also doesn't seem to work.
I had the same problem. I see this question is a little old, but I want to provide a clear and correct answer to save other folks (like me) some time when it pops up in their search results.
It took me a bit of searching and experimenting, but I found the solution. Simply set the ContentMode of the "hidden" ImageView that is inside the UIButton.
[[firstButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
[firstButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
Perhaps that's what Dan Ray was alluding to in his accepted answer, but I suspect not.
If you're dealing with the UIButton's image (as opposed to it's backgroundImage), setting the contentMode on the UIButton itself or on its imageView has no effect (despite what other answers say).
Alternatively do this instead:
self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
self.button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
Or size your image accordingly.
OR just use a UIImageView (which properly respects contentMode) with a UITapGestureRecognizer attached to it, or a transparent UIButton on top of it.
Rather than setting the contentMode on the button itself, you'll want to set contentHorizontalAlignment and contentVerticalAlignment properties and (crucially) the contentMode for the button's imageView for any kind of aspect fill or fit:
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit
You can also do other things like aligning the button's image to the top. If you don't need an aspect fill or fit, you just can set the alignment by itself:
button.contentVerticalAlignment = .top
After a couple of hours of confusion, here's how I got it to work under iOS 3.2. As dusker mentioned, using setBackgroundImage instead of setImage did the job for me.
CGRect myButtonFrame = CGRectMake(0, 0, 250, 250);
UIImage *myButtonImage = [UIImage imageNamed:#"buttonImage"];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:myButtonImage forState:UIControlStateNormal];
[myButton setFrame: myButtonFrame];
[myButton setContentMode: UIViewContentModeScaleAspectFit];
The answer is to use a UIImageView with all the lovely Content Mode settings you want, and then layer a custom button on top of it. Dumb that you can't do that all in one shot, but it appears that you can't.
These two things (which are quite hard to find initially) will stretch your UIButton image to fit the button size:
one should always try to set such in the Storyboard rather than code.
Found a fix for this. Set the adjustsImageWhenHighlighted property of UIButton to NO.
UIButton *b = [[UIButton alloc] initWithFrame:rect];
[b setImage:image forState:UIControlStateNormal];
[b.imageView setContentMode:UIViewContentModeScaleAspectFill];
[b setAdjustsImageWhenHighlighted:NO];
Hope this helps. Feel free to comment below, I will follow up on any questions that you have.
My answer is similar to Kuba's. I needed my image to be programatically set.
UIImage *image = [[UIImage alloc] initWithContentsOfFile:...];
[button setBackgroundImage:image forState:UIControlStateNormal];
button.imageView.contentMode = UIViewContentModeScaleAspectFill; //this is needed for some reason, won't work without it.
for(UIView *view in button.subviews) {
view.contentMode = UIViewContentModeScaleAspectFill;
}
Only solution which worked for me:
[button setImage:image forState:UIControlStateNormal];
button.imageView.contentMode = UIViewContentModeScaleAspectFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
Swift 3
self.firstButton.imageView?.contentMode = .scaleAspectFill
For anyone experiencing this on iOS 15 and Xcode 13, see Matt's answer in this other question.
The behavior of Xcode changed and now defaults UIButtons from the library to the plain style, which prevents the child image from scaling as expected.
Instead of setImage try setBackgroundImage
I believe we have a simple interface builder issue here - apparently the IB ignores any content-mode changes AFTER you have set the image-property.
the solution is as simple: set the content mode, remove previously set image-names (make sure you remove it in all states, default, highlighted etc.), then re-enter the desired image-names in all desired states - et voilĂ .
I also advice to have a look at the adjustsImageWhenHighlighted UIButton property to avoid weird deformations of the image, when the button is pressed.
In trying to figure this out, my method got a bit hackier as time went on, and I wound up subclassing UIButton and overriding setHighlighted:
For me it works to just knock down the image alpha to .5, because they're on a black background.
However, it only works if I comment out [super setHighlighted:] (where it appears the image-stretchy code is going on), which just doesn't feel like the right way to solve this at all...everything seems to be working fine, though. We'll see how it holds up as I keep working on it.
- (void)setHighlighted:(BOOL)highlight {
if (highlight) {
[self.imageView setAlpha:.5];
} else {
[self.imageView setAlpha:1];
}
// [super setHighlighted:highlight];
}
If anyone looking for answer that work in iOS 6 and iOS 7 and storyboard:
You can set image in your storyboard:
And then:
for(UIView* testId in self.subviews) {
if([testId isKindOfClass:[UIImageView class]])
[testId setContentMode:UIViewContentModeScaleAspectFill];
}
If the UIButton does not seem to listen to the layout constraint settings, do check whether the images are larger than the button size. Always use the #2x and #3x images for retina resolutions.

Resources