The size of the button - ios

I put a default button in the Interface builder, and it has some default size
then I programmatically changed its title, and received this:
this is my code for this button:
NSString *btnGetRegisterCodeTitle = NSLocalizedString(#"Get Registration Code", #"Title on button");
[_btnRegister setTitle:btnGetRegisterCodeTitle forState:UIControlStateNormal];
What do i need to do to the button, to make it autolayout its frame so that the entire (3 words ) title would fit on it?

after changing the title call sizeToFit
[yourButton sizeToFit];

What exactly happening here is, When you are changing the title of button, the text becomes out of bound.
What you can do is, programmatically set the button size to fit its content/title.
For that use this:
NSString *btnGetRegisterCodeTitle = NSLocalizedString(#"Get Registration Code", #"Title on button");
[_btnRegister setTitle:btnGetRegisterCodeTitle forState:UIControlStateNormal];
[_btnRegister sizeToFit];
Here the sizeToFit method will automatically resize your UIButton in such a way that your Title is not merged/overlapped.. :)
Update:
Have a look at this Question
I've copied the selected answer from there, in case that question is removed..
Check out the NSString method -sizeWithFont:. It returns a CGSize that will inform you as to how much size your text will need in the button. Then you can adjust the button's frame based on this size, adding whatever padding you desire to the width and height of the button's frame. Something like this:
NSString *msg = #"The button label";
UIFont *font = [UIFont systemFontOfSize:17];
CGSize msgSize = [msg sizeWithFont:font];
CGRect frame = button.frame;
frame.size.width = msg.size.width+10;
frame.size.height = msg.size.height+10;
button.frame = frame;

NSString *btnGetRegisterCodeTitle = NSLocalizedString(#"Get Registration Code", #"Title on button");
CGSize size = [btnGetRegisterCodeTitle sizeWithFont:_btnRegister.titleLabel.font];
[_btnRegister setTitle:btnGetRegisterCodeTitle forState:UIControlStateNormal];
_btnRegister.frame = CGRectMake(_btnRegister.frame.origin.x,
_btnRegister.frame.origin.y,
size.width, size.height);
How about this one?
It is practically the same answer as above, just more simple so you won't get it wrong by mistake. (Using the button title's font instead of system font).
You can still try to add the 10 points to width and height like in the previous answer if you want.

Related

How can I trim the height of UILabel to perfectly fit the text without ever changing font size?

Here is my UILabel (defined by what is in the yellow):
Here is after I add [shortDescriptionLabel sizeToFit]; to end of my code:
Here is a second example (to show that the font size is actually getting changed after sizeToFit:
Here is after I add [shortDescriptionLabel sizeToFit]; to end of my code (it is clear that the font size reverted back to size 30.0):
I would like to trim the excess height (above and below carrots). How can I do this? Here is my current code:
shortDescriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(itemImageView.frame.origin.x+itemImageView.frame.size.width+10, 20, self.tableView.frame.size.width-itemImageView.frame.origin.x- itemImageView.frame.size.width-20-20, tableViewCellHeight/2)];
shortDescriptionLabel.text = itemObject.shortDescription;
shortDescriptionLabel.font = [UIFont boldSystemFontOfSize:30];
shortDescriptionLabel.textAlignment = NSTextAlignmentCenter;
shortDescriptionLabel.adjustsFontSizeToFitWidth = YES;
shortDescriptionLabel.numberOfLines = 0;
shortDescriptionLabel.minimumScaleFactor = 0;
[shortDescriptionLabel setBackgroundColor:[UIColor yellowColor]];
CGFloat fontSize = shortDescriptionLabel.font.pointSize;
NSLog(#"fontSize = %f", fontSize);
Keep in mind that the last NSLog will always display 30.0 (the font size set earlier) even if the displayed font size is obviously smaller than 30.0.
Please help. There seems to be a lot about this online but I can't seem to get anything to work.
Yoh can use sizeToFit but if you want to trim the height and keep the width you can add a height constraint equal to the used UIFont's lineHeight.
AutoLayout
1-Properly Add its Leading,Trailing,Top and bottom Constraints and Write this line of code will do
[label setPreferredMaxLayoutWidth:300.0];
Non AutoLayout
-(CGSize)m_GetHeight:(NSString*)text
{
CGSize constraintSize=[text sizeWithFont:[UIFont fontWithName:#"Arial" size:15.] constrainedToSize:CGSizeMake(182, 2000) lineBreakMode:NSLineBreakByWordWrapping];
return constraintSize;
}

ScrollView can't fit it's subview's content sometimes

I'm trying to let the user to adjust himself the font size to read the content of the app. therefor i put a slider that if the user swipe right, the fonts will grow and left means that the fonts size will be smaller. it works fine, but the problem is that sometimes the scrollView content size is not getting the new content size.
This is my method:
- (IBAction)enlargeLabelWithSlider:(id)sender{
UISlider *slider = (UISlider *)sender;
int font = 0;
int currentSliderValue = (int)slider.value;
if (currentSliderValue<=lastSilderValue) /* Every time the method call, at the end lastSilderValue = currentSliderValue*/
{
// Need to increase
font =lastSilderValue - currentSliderValue;
[self.gameTitleLabel setFont:[UIFont fontWithName:self.gameTitleLabel.font.fontName size:self.gameTitleLabel.font.pointSize+font]];
[self.gameScoreLabel setFont:[UIFont fontWithName:self.gameScoreLabel.font.fontName size:self.gameScoreLabel.font.pointSize+font]];
self.gameStateLabel.font = [UIFont systemFontOfSize:self.gameStateLabel.font.pointSize+font];
}
else
{
// Need to decrease
font =currentSliderValue - lastSilderValue;
[self.gameTitleLabel setFont:[UIFont fontWithName:self.gameTitleLabel.font.fontName size:self.gameTitleLabel.font.pointSize-font]];
[self.gameScoreLabel setFont:[UIFont fontWithName:self.gameScoreLabel.font.fontName size:self.gameScoreLabel.font.pointSize-font]];
self.gameStateLabel.font = [UIFont systemFontOfSize:self.gameStateLabel.font.pointSize-font];
}
lastSilderValue = currentSliderValue;
CGFloat height = self.gameStateLabel.frame.origin.y+self.gameStateLabel.frame.size.height+20;
CGSize size = CGSizeMake(self.ScrollView.frame.size.width, height);
self.ScrollView.contentSize = CGSizeMake(size.width, size.height); // i used self.gameStateLabel.frame.origin.y because it's the last label on the view.
}
can someone tell me why is this happening? Thanks.
I don't see any change to the UILabel frame.
Maybe you have to adapt this frame to the new font size and then try to modify the scrollview contentSize property.
This will be helpful: Adjust UILabel height depending on the text

Not able to change and customize the title of UIButtons in a custom UITableViewCell during runtime

I have created a custom UITableViewCell that contains four UIButtons. The text (titleLabel) for these buttons is generated based on the index of the cell. I am customizing each button in tableView:cellForRowAtIndexPath with the following (answer1 is a UIButton)…
NSLog(#"Default button title: %#", myCustomCell.answer1.titleLabel.text);
[myCustomCell.answer1 setTitle:selectedQuestion.possibleAnswers[0] forState:UIControlStateNormal];
myCustomCell.answer1.titleLabel.textAlignment = NSTextAlignmentCenter;
NSLog(#"New button title: %#", myCustomCell.answer1.titleLabel.text);
[myCustomCell.answer1 adjustTitleFontSizeToFit];
Expected Output:
Default button title: Answer 1
New button title: *ANSWER TEXT HERE*
But the actual console output shows the string not updating, but on the device it is the correct string. However, it sometimes does change the title, but only of the first button I create (I am using this same code on each button).
I created a category of UIButton with the adjustTitleFontSizeToFit method because I want the titleLabel of each button to auto size the font if the string doesn’t fit in the button frame. When testing this method outside of this example, it works as expected. The problem seems to be that the titleLabel of the button is not updating in time for adjustTitleFontSizeToFit to do it’s work. In other words, when adjustTitleFontSizeToFit is called on the button, the string it operates on is the default string that is in the xib when I created the buttons. An NSLog after setTitle:forState: also shows this.
The strange behavior (strange to me anyway) is that in app, it does actually change the title. I just need to be able to work on the titleLabel during the cell building so I can resize the button label.
Any ideas are much appreciated and I can provide more info if needed.
As with many UI bugs, the problem was a simple checkmark that was missed in my xib/storyboard. I had the first button set as a 'custom' button type and the rest were set as system 'button' types.
The give-away should have been that it was working for the one button, but not the others. But in case anyone runs across a similar problem, I'll leave this up.
And if anyone needs to resize the font size of a UIButton, here is category method I used...
- (void)adjustTitleFontSizeToFit
{
UIFont *font = self.titleLabel.font;
CGSize size = self.frame.size;
for (CGFloat maxSize = self.titleLabel.font.pointSize; maxSize >= self.titleLabel.minimumScaleFactor * self.titleLabel.font.pointSize; maxSize -= 1.f) {
font = [font fontWithSize:maxSize];
CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
CGSize labelSize = [self.titleLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelSize.height <= size.height) {
self.titleLabel.font = font;
[self setNeedsLayout];
break;
}
}
// set the font to the minimum size anyway
self.titleLabel.font = font;
[self setNeedsLayout];
}

iOS: sizeWithFont: for custom font

I've been plugging away and I need to use the sizeWithFont: method to properly line up my layout, but it doesn't seem to work with custom fonts. Is there a way to get it to work, or maybe another method I can use?
I'm pretty stumped on this. Any help is appreciated.
sizeWithFont should definitely work, but if it's giving you a problem then there is a workaround. You can put the text in a UITextView, add it to your layout, and then retrieve the actual text size and adjust accordingly. Here's some sample code from one of my projects:
// Put in the title in
self.titleView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 195, 195)];
self.titleView.font = [UIFont fontWithName:#"Bliss Pro" size:20.0];
[self addSubview:self.titleView];
self.titleView.text = #"Add your text here";
// Now get the actual size of the text and resize the title view's frame
CGRect frame = self.titleView.frame;
frame.size.height = self.titleView.contentSize.height;
self.titleView.frame = frame;
It's a bit hackish, but it certainly works.
#define kFontSize 14.0 //modify your font size
CGSize size = [yourView sizeWithFont:[UIFont boldSystemFontOfSize:kFontSize]];

UILabel - auto-size label to fit text?

Is it possible to auto-resize the UILabel box/bounds to fit the contained text?
(I don't care if it ends up larger than the display)
So if a user enters "hello" or "my name is really long i want it to fit in this box", it is never truncated and the label is 'widened' accordingly?
Please check out my gist where I have made a category for UILabel for something very similar, my category lets a UILabel stretch it's height to show all the content: https://gist.github.com/1005520
Or check out this post: https://stackoverflow.com/a/7242981/662605
This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:
#implementation UILabel (dynamicSizeMeWidth)
- (void)resizeToStretch{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
#end
You could more simply use the sizeToFit method available from the UIView class, but set the number of lines to 1 to be safe.
iOS 6 update
If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.
iOS 8 update
sizeWithFont: is deprecated so use sizeWithAttributes: instead:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:#{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
Using [label sizeToFit]; will achieve the same result from Daniels Category.
Although I recommend to use autolayout and let the label resize itself based on constraints.
If we want that UILabel should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this
Steps
Put UILabel in view controller and place it wherever you want. Also put 0 for numberOfLines property of UILabel.
Give it Top, Leading and Trailing space pin constraint.
Now it will give warning, Click on the yellow arrow.
Click on Update Frame and click on Fix Misplacement. Now this UILabel will shrink if text is less and expand if text is more.
This is not as complicated as some of the other answers make it.
Pin the left and top edges
Just use auto layout to add constraints to pin the left and top sides of the label.
After that it will automatically resize.
Notes
Don't add constraints for the width and height. Labels have an intrinsic size based on their text content.
Thanks to this answer for help with this.
No need to set sizeToFit when using auto layout. My complete code for the example project is here:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel!
#IBAction func changeTextButtonTapped(sender: UIButton) {
myLabel.text = "my name is really long i want it to fit in this box"
}
}
If you want your label to line wrap then set the number of lines to 0 in IB and add myLabel.preferredMaxLayoutWidth = 150 // or whatever in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)
If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.
Use [label sizeToFit]; to adjust the text in UILabel
Here's what I am finding works for my situation:
1) The height of the UILabel has a >= 0 constraint using autolayout. The width is fixed.
2) Assign the text into the UILabel, which already has a superview at that point (not sure how vital that is).
3) Then, do:
label.sizeToFit()
label.layoutIfNeeded()
The height of the label is now set appropriately.
I created some methods based Daniel's reply above.
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
CGSize maximumLabelSize = CGSizeMake(290, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
return expectedLabelSize.height;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label
{
CGRect newFrame = label.frame;
newFrame.size.height = [self heightForLabel:label withText:label.text];
label.frame = newFrame;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
label.text = text;
[self resizeHeightToFitForLabel:label];
}
#implementation UILabel (UILabel_Auto)
- (void)adjustHeight {
if (self.text == nil) {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
return;
}
CGSize aSize = self.bounds.size;
CGSize tmpSize = CGRectInfinite.size;
tmpSize.width = aSize.width;
tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}
#end
This is category method. You must set text first, than call this method to adjust UILabel's height.
You can size your label according to text and other related controls using two ways-
For iOS 7.0 and above
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{
NSFontAttributeName : labelFont
}
context:nil].size;
before iOS 7.0 this could be used to calculate label size
CGSize labelTextSize = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
// reframe other controls based on labelTextHeight
CGFloat labelTextHeight = labelTextSize.height;
If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-
[label setNumberOfLines:0]; // for multiline label
[label setText:#"label text to set"];
[label sizeToFit];// call this to fit size of the label according to text
// after this you can get the label frame to reframe other related controls
Add missing constraints in storyboard.
Select UILabel in storyboard and set the attributes "Line" to 0.
Ref Outlet the UILabel to Controller.h with id:label
Controller.m and add [label sizeToFit]; in viewDidLoad
the sizeToFit() method doesn't play well with constraints, but as of iOS 9 this is all you need -
label.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width).activate()
I had a huge problems with auto layout.
We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.
The missing ingredient was bottom constraint for description.
I've changed bottom constraint of dynamic element from = 0 to >= 0.
Fits everytime! :)
name.text = #"Hi this the text I want to fit to"
UIFont * font = 14.0f;
CGSize size = [name.text sizeWithAttributes:#{NSFontAttributeName: font}];
nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
nameOfAssessment.font = [UIFont systemFontOfSize:font];
you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more
[self.yourLableName sizeToFit];
There's also this approach:
[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];

Resources