Place UIButton with dynamic tex at the center of UITableViewCell - ios

I have a UIButton in table cell. I want to place the button at the center of the cell. The text of the button is dynamic. This is what I have tried, but it's not coming at the center. It is coming towards the right of center.
UIButton *btnName = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGSize maximumLabelSize = CGSizeMake(self.frame.size.width, MAXFLOAT);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;
NSDictionary *attr = #{NSFontAttributeName: [UIFont systemFontOfSize:15]};
CGRect labelBounds = [titleText boundingRectWithSize:maximumLabelSize
options:options
attributes:attr
context:nil];
CGFloat width = ceilf(labelBounds.size.width);
btnName.frame = CGRectMake(0.0, imgPic.frame.origin.y+imgPic.frame.size.height+20.0, width, 20.0);
btnName.center = CGPointMake(cell.contentView.center.x, imgPic.frame.origin.y+imgPic.frame.size.height+10.0);
[btnName setTitle:titleText forState:UIControlStateNormal];
[btnName setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[cell.contentView addSubview:btnName];

Just add below line in your code.
btnName.center = cell.center;

Your code looks fine, only you've to make these change,
You should center the button after you add it cell, and
Correct the center points
[cell.contentView addSubview:btnName];
btnName.center = CGPointMake(cell.frame.size.width/2.f, btnName.center.y);

Vladimir's answer saved my day. I used setAutoresizingMask and now it is coming absolutely fine.

Related

How can we fix UItextfields text and UIbuttons title labels exactly at center position

Hi i am beginner in ios and i am trying to insert UItextfield "text" data exactly at center of the y-axis as like below textfield image
And i would like to insert UIbutton "titleLabel text" exactly center of x-axis and center of y-axis as like below button image for this i tried lot but i did not get result please help me some one
my code:-
[self.TripIdTxt setValue:[UIColor blackColor] forKeyPath:#"_placeholderLabel.textColor"];
self.TripIdTxt.layer.sublayerTransform = CATransform3DMakeTranslation(10.0f, 0.0f, 0.0f);
self.TripIdTxt.backgroundColor = [UIColor whiteColor];
self.TripIdTxt.layer.cornerRadius = 3.0f;
self.TripIdTxt.layer.masksToBounds = YES;
[self.TripIdTxt setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self.TripIdTxt setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
self.TripIdTxt.textColor = [UIColor blackColor];
self.TripIdTxt.font = [UIFont fontWithName:bitter_Regular size:14];
set
for UIButton
yourbtnName.titleLabel.textAlignment = NSTextAlignmentCenter;
for y-axis
[yourbtnName setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
for X-axis
[yourbtnName setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
for UITextFields
yourtextfieldName.textAlignment = NSTextAlignmentCenter;
diectly you can access in storyboard like
for additional information see this link
Padding with TextField
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
TripIdTxt.leftView = paddingView;
self. TripIdTxt.leftViewMode = UITextFieldViewModeAlways;
or else use Transform
TripIdTxt.layer.sublayerTransform = CATransform3DMakeTranslation(10.0f, 0.0f, 0.0f);
Set the text alignmaent center of your lable property .
mainlabel.textAlignment = NSTextAlignmentCenter;
u set its alignment using xib by
u can also set its vertical alignment using xib by
Programmatically U can set Content's vertical alignment for textfield as well as button as
button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
txtField.contentVerticalAlignment = UIControlContentHorizontalAlignmentRight;
Hope it helps.
Happy Coding.. :)

how can we set Button title labels exactly at center of both x-axis and y-axis

Hi i am beginner in Ios and i am trying to inserted UIButton on my ViewController
Here i want to insert button "titlelabel" exactly at center of x-axis and center of y-axis and according to my below code button title label coming like below image please help me what should i do for set that "titlelabel" exactly center of x and y axis
my code:-
NextBtn_2 = [UIButton buttonWithType:UIButtonTypeCustom];
NextBtn_2.frame = CGRectMake(190, 330, 120, 30);
[NextBtn_2 setTitle:#"NEXT" forState:UIControlStateNormal];
NextBtn_2.titleLabel.font = [UIFont fontWithName:bitter_Bold size:14];
[NextBtn_2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[NextBtn_2 addTarget:self action:#selector(NextBtn_2_Clicked) forControlEvents:UIControlEventTouchUpInside];
NextBtn_2.titleLabel.textAlignment = NSTextAlignmentCenter;
[NextBtn_2 setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[NextBtn_2 setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
NextBtn_2.layer.cornerRadius = 3.0f;
NextBtn_2.layer.masksToBounds = YES;
NextBtn_2.backgroundColor = [self colorWithHexString:#"a53129"];
[self.view addSubview:NextBtn_2];
Please try below Property of UIButton
NextBtn_2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
NextBtn_2.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
NextBtn_2.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
Hope this is work for you.
Thanks :)
Try to set titleEdgeInsets of your button title lable .
NextBtn_2.titleEdgeInsets = UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) ;
hope it works for you .

Move UIButton in UIView when UILabel is resized dynamically. iOS

I have a UILabel and a UIButton inside of a Custom UIView. My UIButton site below my UILabel.
My UILabel text however changes it's size and overlaps my UIButton.
I want to be able to move my UIButton down when the UILabel resizes itself?
I only have managed to dynamically resize my UILabel but have not been able to resize or move my UIButton.
self.chosenCategoriesLabel.font = [UIFont fontWithName:#"Helvetica-Light" size:17.0];
self.chosenCategoriesLabel.textColor = [UIColor colorWithRed:161.0/255.0 green:205.0/255.0 blue:86.0/255.0 alpha:1.0];
self.chosenCategoriesLabel.font = [UIFont fontWithName:#"Helvetica-Light" size:15.0];
self.chosenCategoriesLabel.numberOfLines = 0;
self.selectedCategoriesString = [self.selectedCategoriesArray componentsJoinedByString:#","];
self.chosenCategoriesLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.chosenCategoriesLabel.text = [self.selectedCategoriesString stringByAppendingString:#"\n\n\n\n"];
[self.selectionsWrapper addSubview:self.chosenCategoriesLabel];
self.chosenCategoriesLabel.frame = CGRectMake(self.chosenCategoriesLabel.frame.origin.x, self.chosenCategoriesLabel.frame.origin.y, self.chosenCategoriesLabel.frame.size.width, [self sizeLabel]);
[self.itemThumbnail setImageWithURL:self.item.itemImageURL placeholderImage:[UIImage imageNamed:#"profile-image-placeholder"]];
[self.view addSubview:self.itemThumbnail];
[self.selectCategorieButton setTitle:#"Select Categories" forState:UIControlStateNormal];
[self.selectCategorieButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.selectCategorieButton setTitle:#"Select Categories" forState:UIControlStateHighlighted];
[self.selectCategorieButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
self.selectCategorieButton.titleLabel.font = lightHelveticaFont;
[self.selectCategorieButton setBackgroundImage:[UIImage imageNamed:#"btn_choose_categories.png"] forState:UIControlStateNormal];
[self.selectCategorieButton setBackgroundImage:[UIImage imageNamed:#"btn_choose_categories.png"] forState:UIControlStateHighlighted];
[self.selectCategorieButton.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
[self.selectCategorieButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Light" size:15.0]];
[self.selectionsWrapper addSubview:self.selectCategorieButton];
[self changeLabel];
self.chosenCategoriesLabel.frame = CGRectMake(self.chosenCategoriesLabel.frame.origin.x, self.chosenCategoriesLabel.frame.origin.y, self.chosenCategoriesLabel.frame.size.width, [self sizeLabel]);
-(void)changeLabel {
self.chosenCategoriesLabel = [NSString stringWithFormat:#"%#",array];
self.chosenCategoriesLabel.frame = CGRectMake(self.chosenCategoriesLabel.frame.origin.x, self.chosenCategoriesLabel.frame.origin.y, self.chosenCategoriesLabel.frame.size.width, [self sizeLabel]);
}
- (CGFloat) sizeLabel
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CGSize sizeToFit = [self.chosenCategoriesLabel.text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:CGSizeMake(276.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
#pragma clang diagnostic pop
return fmaxf(22.0f, sizeToFit.height + 40); }
A couple of things...
I'm not sure why you are re-adding the UI components again when you say you've created them in IB? For example, you shouldn't need lines like the following if the controls are already in the view
[self.selectionsWrapper addSubview:self.chosenCategoriesLabel];
You also execute this line twice?
self.chosenCategoriesLabel.frame = CGRectMake(self.chosenCategoriesLabel.frame.origin.x, self.chosenCategoriesLabel.frame.origin.y, self.chosenCategoriesLabel.frame.size.width, [self sizeLabel]);
To adjust the frame of your button do something like this...
// Get the original frames;
CGRect buttonFrame = self.selectCategorieButton.frame;
CGRect labelFrame = self.chosenCategoriesLabel.frame;
//Work out the new height
CGFloat newHeight = [self sizeLabel];
//Work out what the difference is
CGFloat adjustment = newHeight - labelFrame.size.height;
//Set the labels new height
labelFrame.size.height = newHeight;
self.chosenCategoriesLabel.frame = labelFrame;
//add the difference to the buttons frame
buttonFrame.origin.y = buttonFrame.origin.y + adjustment;
self.selectCategorieButton.frame = buttonFrame;
Depending on how you've defined you custom view you might also have to adjust the height of that as well to accommodate the new position of the button?

Center vertically in UILabel with autoshrink

This is a little different from all the other "How do I center the text in a UILabel" questions here...
I have a UILabel with some text in it, I want to center the text vertically in the UILabel. What's the big deal, right? That's the default. The problem comes because my text is dynamic and I have autoshrink turn on. As the text grows larger, the font size shrinks. You get this behavior.
Notice that the font baseline has not moved, I want it to move so the numbers are centered vertically in the UILabel's frame.
Easy, right? I just remember the frame's original center in viewDidLoad
self.workoutTimeCenter = _workoutTimeLabel.center;
and then I call sizeToFit after I change the the text, right?
[_workoutTimeLabel sizeToFit];
_workoutTimeLabel.center = _workoutTimeCenter;
Well, sizeToFit did, I guess, exactly what it was supposed to do, resize the frame so the text fits without shrinking!
How can I vertically center the text in a UILabel while respecting baselines and autoshrink? (Note, an iOS5 and later solution is fine and I can even deal with an iOS6 and later solution.)
In my experience you can just set the -[UILabel baselineAdjustment] property to UIBaselineAdjustmentAlignCenters to achieve the effect you're describing.
From the docs:
baselineAdjustment
Controls how text baselines are adjusted when text
needs to shrink to fit in the label.
#property(nonatomic) UIBaselineAdjustment baselineAdjustment
Discussion
If the adjustsFontSizeToFitWidth property is set to YES,
this property controls the behavior of the text baselines in
situations where adjustment of the font size is required. The default
value of this property is UIBaselineAdjustmentAlignBaselines. This
property is effective only when the numberOfLines property is set to
1.
and
UIBaselineAdjustmentAlignCenters
Adjust text based relative to the center of its bounding box.
EDIT: adding a full view-controller that demonstrates this:
#interface TSViewController : UIViewController
#end
#implementation TSViewController
- (void) addLabelWithFrame: (CGRect) f baselineAdjustment: (UIBaselineAdjustment) bla
{
UILabel* label = [[UILabel alloc] initWithFrame: f];
label.baselineAdjustment = bla;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont fontWithName: #"Courier" size: 200];
label.text = #"00";
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];
label.userInteractionEnabled = YES;
[self.view addSubview: label];
UIView* centerline = [[UIView alloc] initWithFrame: CGRectMake(f.origin.x, f.origin.y+(f.size.height/2.0), f.size.width, 1)];
centerline.backgroundColor = [UIColor redColor];
[self.view addSubview: centerline];
UITapGestureRecognizer* tgr = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector(onTap:)];
[label addGestureRecognizer: tgr];
}
- (void) viewDidLoad
{
[super viewDidLoad];
[self addLabelWithFrame: CGRectMake(0, 0, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignCenters];
[self addLabelWithFrame: CGRectMake(0, 220, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
}
- (void) onTap: (UITapGestureRecognizer*) tgr
{
UILabel* label = (UILabel*)tgr.view;
NSString* t = [label.text stringByAppendingString: #":00"];
label.text = t;
}
#end
when working in IB, be sure to set align baselines to center
Note: line break CANNOT be word wrap for this to work, so it will NOT work multiline (good to set the line break to Truncate tail)
-(void)fitVerticallyToLabel:(UILabel *)lbl
{
CGFloat fontSize = lbl.frame.size.width / lbl.text.length;
[lbl setFont:[UIFont fontWithName:#"Helvetica-Bold" size:fontSize]];
CGRect rect = lbl.frame;
rect.origin.y += rect.size.height - fontSize;
rect.size.height = fontSize;
[lbl setFrame:rect];
}
How to Use: Call this method after setting the text to your label.
label.text = #"text";
[self fitVerticallyToLabel:label];
Note: I ahev taken UILabel from xib. You can take it programmatically too in that case you will have to set its text alignment NSTextAlignMentCenter
Try to implement this logic:
-(void)adjustLabel1Text1:(NSString *)text1
{
UILabel *lbl_first = [UIFont fontWithName:#"Helvetica" size:12];
text1 = [text1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
float hedingLblHeight = [self calculateHeightOfTextFromWidth:text1 : [UIFont fontWithName:#"Helvetica" size:12] :118 :UILineBreakModeWordWrap];
lbl_first.text=text1;
[lbl_first setFrame:CGRectMake(lbl_first.frame.origin.x, lbl_first.frame.origin.y, 118, hedingLblHeight)];
lbl_first.lineBreakMode = UILineBreakModeWordWrap;
lbl_first.numberOfLines = 0;
[lbl_first sizeToFit];
//////////Adjust the lable or any UIControl below this label accordingly.
float endResultHeight=[self calculateHeightOfTextFromWidth:text2 : [UIFont fontWithName:#"Helvetica" size:15] :299 :UILineBreakModeWordWrap];
if(hedingLblHeight>secondImgTitleHeight)
{
[lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
}
else
{
[lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
}
lbl_endResult.lineBreakMode=UILineBreakModeWordWrap;
lbl_endResult.numberOfLines = 0;
[lbl_endResult sizeToFit];
}
-(float) calculateHeightOfTextFromWidth:(NSString*)text : (UIFont*) withFont:(float)width :(UILineBreakMode)lineBreakMode
{
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
return suggestedSize.height;
}
It has helped me a lot.Hope it works for you.
Try
yourLabel.textAlignment = UITextAlignmentCenter;

Stretch the image to fit on button depending on length of text in iOS 5

I have one image that I want to add as background image to uibutton. I want to stretch the image to fit button width. User will enter the title for button at runtime.So depending on width of text entered by user , it will strech the image. Beyond a certain width of the button , the button will not stretch further but instead the text will get truncated. Here is my code
CGSize suggestedSize = [self.strButtonTitle sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSLog(#"Widht:- %f",suggestedSize.width);
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
customButton.frame = CGRectMake(50, 200, 75, 40);
CGRect frame = customButton.frame;
frame.size.width = suggestedSize.width;
if (frame.size.width > 75) {
frame.size.width = 75;
customButton.frame = frame;
}
else {
frame.size.width +=5;
customButton.frame = frame;
}
NSLog(#"Custom button width:- %f",customButton.frame.size.width);
UIImage *buttonImageNormal = [UIImage imageNamed:BUTTON_IMAGE];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[customButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
[customButton setTitle:self.strButtonTitle forState:UIControlStateNormal];
[customButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:customButton];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = barButton;
[barButton release];
My problem is , button width doesn't increase according to text entered by user.
If user enter ppppp, width doesn't increase upto 75 instead it is showing "pp...p"
Any knid of help is highly appreciated. Thanks.
The problem is in measuring the width of string. You are measuring the width of string by below way.
CGSize suggestedSize = [self.strButtonTitle sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
Here you are using systemFont with size as FONT_SIZE.
However you are not setting the same font to your customButton textlabel. It can be done by below way.
[customButton.titleLabel setFont:[UIFont systemFontOfSize:FONT_SIZE]];
Hope it will help.

Resources