Move UIButton in UIView when UILabel is resized dynamically. iOS - 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?

Related

getting element from array one by one and createbutton

I have a UItextFeild as search bar on clicking a tableview with suggestion open.now i want to click on that row and make a button with its label in below view as described in image .how can i acheive this
I want it one by one means when i click on row it create a button on view and UITableView hide then again i start searching and on again clicking on some other row make a button with different value of X.
_selectednames = [NSMutableArray arrayWithCapacity:self.sortedArray.count];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// MGContactItemsModel *model = _arrayForContacts[indexPath.row];
self.searchText.text = [NSString stringWithFormat:#"%#",[_sortedArray objectAtIndex:indexPath.row]];
self.tableView.hidden = YES;
[_selectednames addObject:_searchText.text];
for (int i; i < _selectednames.count ; i++) {
[self makeLabelsAndButtons:i];
}
now in my makeLabelsAndButtons funtion i done something like this
CGFloat xOffset = 10.0f;
int buttonCount = 0;
CGRect buttonFrame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
NSString *nameString = [self.selectednames objectAtIndex:indexPath];
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
//_button.frame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
for(int i=buttonCount; i >0;i++) {
xOffset = xOffset+10;
buttonFrame.origin.x += buttonFrame.size.width+xOffset;
}
_button.frame = buttonFrame;
buttonCount++;
_button.tag = indexPath;
//button.center = CGPointMake(xOffset, 10.0f);
//[button setBackgroundImage:[UIImage imageNamed:picString] forState: UIControlStateNormal];
[_button setTitle:self.selectednames[indexPath] forState:UIControlStateNormal];
_button.backgroundColor = [UIColor lightGrayColor];
_button.titleLabel.font = [UIFont fontWithName:#"Arial" size:8.0f];
_button.layer.cornerRadius = 10.0f;
_button.layer.masksToBounds = YES;
[self.buttonView addSubview:_button];
NSLog(#"name: %#", nameString);
also on clicking button it will removed.any help would be thankful.
It works for me.Please try it.
y=20;
x=20;
for (int i=0; i<[arrAssignUsers count]; i++) {
CGRect screenRect=[[UIScreen mainScreen]bounds];
CGFloat screenWidth=screenRect.size.width;
[arrBtnStatus addObject:[NSNumber numberWithBool:NO]];
NSString *strNames=[arrAssignUsers objectAtIndex:i];
stringsize=[strNames sizeWithAttributes:
#{NSFontAttributeName: [UIFont systemFontOfSize:20.0f]}];
btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat m=x+stringsize.width+10;
CGFloat n=screenWidth-20;
if (m<=n) {
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width +10;
}
else
{
y=y+stringsize.height+10;
x=20;
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width+10;
}
[btn setTitle:self.arrAssignUsers[i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.tag=i;
[btn addTarget:self
action:#selector(notifyButtonPressedInEditTask:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor=WHITE_COLOR;
btn.layer.cornerRadius=10;
[btn.layer setMasksToBounds:YES];
btn.layer.borderWidth=2.0f;
btn.layer.borderColor=[UIColor orangeColor].CGColor;
[self checkNotifybtnStatus:btn];
[cell addSubview:btn];
}
}
It may helps to you.Thank you
You can use UICollectionView to create buttons. All you need to do is
1. Create custom cell with button as you want
2. When you tap on table view cell, add item to array and reload UICollectionView
3. Show buttons and it will automatically add scrollview for you.
When you tap on UICollectionView cell, remove object from array and reload UICollectionView again.
This will more easy as compared to adding buttons and setting frames.
And design UICollectionView cell in such way that it will same length as your text, use NSLayoutConstraints for it. It will work fast and smooth.
Code will be minimum and reusable.
Try out this working code...
Take UIScrollView in your Xib for buttons
//Adding menu buttons
btnArray = #[#"SYMPTOMATIC", #"SOCIAL", #"VOCATIONAL", #"PERSONAL"];
[self addButtonsInScrollMenu:btnArray];
/**
* Add Menu Buttons in Menu Scroll View
*
* #param buttonArray Array containing all menu button title
*/
#pragma mark - Add Menu Buttons in Menu Scroll View
-(void) addButtonsInScrollMenu:(NSArray *)buttonArray
{
CGFloat buttonHeight = self.menuScrollView.frame.size.height;
CGFloat cWidth = 0.0f;
for (int i = 0 ; i<buttonArray.count; i++)
{
NSString *tagTitle = [buttonArray objectAtIndex:i];
CGFloat buttonWidth = [self widthForMenuTitle:tagTitle buttonEdgeInsets:kDefaultEdgeInsets];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(cWidth, 0.0f, buttonWidth, buttonHeight);
[button setTitle:tagTitle forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"Roboto-Regular" size:12.0f];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.menuScrollView addSubview:button];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, button.frame.size.height - kButtonBorderHeight, button.frame.size.width, kButtonBorderHeight)];
bottomView.backgroundColor = [UIColor darkTextColor];
bottomView.tag = 1001;
[button addSubview:bottomView];
if (i == 0)
{
button.selected = YES;
[bottomView setHidden:NO];
}
else
{
[bottomView setHidden:YES];
}
cWidth += buttonWidth;
}
NSLog(#"scroll menu width->%f",cWidth);
self.menuScrollView.contentSize = CGSizeMake(cWidth, self.menuScrollView.frame.size.height);
}

How to make the UIButton title label font same in size regardless of the text width

I am generating few buttons that should look like a tabbar. This is what I have done.
scrolTab=[[UIScrollView alloc] initWithFrame:CGRectMake(0, h-48, w, 48)];
[scrolTab setContentInset:UIEdgeInsetsMake(0.0, 0.0, 0.0, 180.0)];
[scrolTab setShowsHorizontalScrollIndicator:NO];
[self.view addSubview:scrolTab];
for (int i=1; i<6; i++) {
[scrolTab addSubview:[self GetTabBarItems:i :5]];
}
Then my GetTabBarItems method is like this.
-(UIButton *)GetTabBarItems :(NSInteger)index:(NSInteger)count
{
UIButton *item=[[UIButton alloc] initWithFrame:CGRectMake(tabbuttonX, 0, w/count,49)];
[item.titleLabel setFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:10.0]];
item.titleLabel.numberOfLines = 1;
item.titleLabel.adjustsFontSizeToFitWidth = YES;
item.titleLabel.lineBreakMode = NSLineBreakByClipping;
CGSize imageSize=item.imageView.image.size;
CGFloat space=6.0;
if (index==1) {
[item setTitle:#"Menu" forState:UIControlStateNormal];
[item setImage:[UIImage imageNamed:#"MenuBtn"] forState:UIControlStateNormal];
}
else if (index==2) {
[item setTitle:#"My Profile" forState:UIControlStateNormal];
[item setImage:[UIImage imageNamed:#"ProfTab"] forState:UIControlStateNormal];
}
else if (index==3) {
[item setTitle:#"Notification" forState:UIControlStateNormal];
[item setImage:[UIImage imageNamed:#"Notification"] forState:UIControlStateNormal];
}
else if (index==4)
{
[item setTitle:#"Things-Todo" forState:UIControlStateNormal];
[item setImage:[UIImage imageNamed:#"ThingsTodo"] forState:UIControlStateNormal];
}
else if (index==5)
{
[item setTitle:#"Search" forState:UIControlStateNormal];
[item setImage:[UIImage imageNamed:#"Search"] forState:UIControlStateNormal];
}
[item setTitleEdgeInsets:UIEdgeInsetsMake(-(imageSize.height+(-20)), -10.0, -(imageSize.height+space), 10.0)];
CGSize titleSize=[item.titleLabel.text sizeWithAttributes:#{NSFontAttributeName: item.titleLabel.font}];
CGRect txtLabelframe=item.titleLabel.frame;
item.imageEdgeInsets = UIEdgeInsetsMake(0.0, -(txtLabelframe.size.width+txtLabelframe.origin.x)/2, 10.0, - titleSize.width);
tabbuttonX=tabbuttonX+item.frame.size.width;
return item;
}
I want to make my font is in same size, But if I make those fonts in same size its truncate from the middle and middle of the text shows as dots. How can I make those fonts looks like in same size and show the full text in the button.
Please help me. This is my output for this code.
Thanks
Don't add button title, you have to add another label as subview to the button
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(-10, button.frame.size.height-20, 100, 30)];//adjust the frame as you required
[label2 setTextColor:[UIColor redColor]];
label2.text = #"lengthy string is here";
[label2 setFont:[UIFont fontWithName:button.titleLabel.font.fontName size:button.titleLabel.font.pointSize]];
[button addSubview:label2];
If the label touches the near button, Use this code
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(-10, button.frame.size.height-20, 150, 60)]; //adjust the frame as your string length
[label2 setTextColor:[UIColor redColor]];
NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:#"lengthy string\nshould be here"];
label2.numberOfLines = 0;
[label2 setAttributedText:muAtrStr];
[label2 setFont:[UIFont fontWithName:button.titleLabel.font.fontName size:button.titleLabel.font.pointSize]];
[button addSubview:label2];
First try to remove this line
item.titleLabel.adjustsFontSizeToFitWidth = YES;
I guess that the font will now remain equal size but gets clipped ?
Try to use the iOS Simulator debug option "Color Blended Layer" or the Xcode 6 View Debugging Option and see if the label is big enough.
Ah and methods usually starts with a lower case letter ;)

keep label text aligned center to screen while scrolling uilabel with view iOS?

I have a UITableView and 10 sections in it.
For each section I have a custom header.
In custom header I have a label as heading of section with text value date.
Table content size is (450,1000).
Here my label with text is also scrolling, but I want my label text should aligned center to screen and it should not scroll horizontally with table.
Thanks in advance.
After knocking my head for hours finally i got this solution.
Simply i used
(void)scrollViewDidScroll:(UIScrollView *)scrollView*
method and changed my label frame with table view content offset.
myLabel.frame = CGRectMake(tableview.contentoffset.x, 0, deviceHeight, 27);
It will keep my label at same position to screen, logically it is changing but will look like its stable at same position.
That behavior is only common when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.
May be the following links will help you to solve your problem:
1. UITableView with fixed section headers
2. https://corecocoa.wordpress.com/2011/09/17/how-to-disable-floating-header-in-uitableview/
- (void)addButtonsOnScrollViewHorizontal:(int)postion :(UIScrollView*)scrollView
{
[scrollView setShowsVerticalScrollIndicator:NO];
float x = 30;
for (int i = 1; i <=postion; i++)
{
UIButton *button= [UIButton buttonWithType:UIButtonTypeCustom];
[button setTag:i];
[button setTitle:[NSString stringWithFormat:#"%i",i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:26.0f/255.0f green:188.0f/255.0f blue:156.0f/255.0f alpha:100.0f] forState:UIControlStateSelected];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:18.0f];
CGSize maxSize = CGSizeMake(button.frame.size.width, FLT_MAX);
CGRect labRect = [button.titleLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:button.titleLabel.font} context:nil];
[button setFrame:CGRectMake(x, 0, labRect.size.width+10, 30)];
[button addTarget:self action:#selector(scrollViewDaysbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
if (i==postion)
{
[_scrollViewDays setContentOffset:CGPointMake (button.frame.origin.x+button.frame.size.width/2-70, 0) animated:NO];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
[button setSelected:YES];
currentSelectionDays =i;
}
[scrollView addSubview:button];
x +=labRect.size.width+20;
}
scrollView .contentSize = CGSizeMake(x, 0);
}
-(void)scrollViewDaysbtnClicked:(UIButton*)sender
{
for (UIButton *button in _scrollViewDays.subviews)
{
if ([button isKindOfClass:[UIButton class]])
{
if (button.tag == sender.tag)
{
[_scrollViewDays setContentOffset:CGPointMake (button.frame.origin.x+button.frame.size.width/2-70, 0) animated:NO];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
[button setSelected:YES];
currentSelectionDays =(int)sender.tag;
}else
{
[button setSelected:NO];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:18.0f];
}
}
}
}
use it....

How to add Dynamic elements in the reverse direction to a Uiscrollview in IOS?

I had a scrollview in my application with dynamic elements which i am adding from right to left like this
if(array.count>0)
{
[[cell.contentView viewWithTag:777] removeFromSuperview];
float x=315.0;
float width=0.0;
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(70, 52,245,20)];
scroll.backgroundColor=[UIColor clearColor];
scroll.tag=777;
[scroll setContentOffset:CGPointMake(70,245)];
scroll.showsHorizontalScrollIndicator=NO;
for(int i =0; i <[array count] ; i++)
{
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundColor:[UIColor colorWithRed:133.0/255.0 green:155.0/255.0 blue:179.0/255.0 alpha:1.0]];
btn.layer.cornerRadius = 2;
[btn setTitle:[[array objectAtIndex:i] objectForKey:#“ggg”] forState:UIControlStateNormal];
btn.userInteractionEnabled=NO;
[btn.titleLabel setFont:[UIFont fontWithName:#"Helvetica Neue" size:10.0]];
CGSize size = [btn.titleLabel.text sizeWithAttributes:
#{NSFontAttributeName:
[UIFont fontWithName:#"Helvetica Neue" size:10.0]}];
x=x-(size.width+10);
//or whatever font you're using
[btn setFrame:CGRectMake(x,0,size.width+10,15)];
[scroll addSubview:btn];
width=width+x;
x=x-5;
}
scroll.contentSize=CGSizeMake((width+50),20);
// [scroll setPagingEnabled:YES];
[cell.contentView addSubview:scroll];
}
here everything working very fine,but i am not able to scroll to the last element added at the left.scroll was only allowing me to scroll up to 70 from left to right .Can anybody tell me where i am going wrong on this?
-(void)addButtonInScrollViewFromArray:(NSArray *)array{
NSInteger arrayCount=array.count;
NSInteger numberIteration=0;
CGFloat buttonXValue=300;
UIScrollView *buttonScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, 360, 60)];
while (numberIteration<arrayCount) {
UIButton *buttonCreated=[UIButton buttonWithType:UIButtonTypeCustom];
buttonCreated.frame=CGRectMake(buttonXValue,5, 50, 50);
buttonXValue-=60;
[buttonCreated setTitle:[NSString stringWithFormat:#"Button%d",numberIteration] forState:UIControlStateNormal];
[buttonScrollView addSubview:buttonCreated];
numberIteration++;
}
CGFloat totalLength=numberIteration*60;
buttonScrollView.contentSize=CGSizeMake(totalLength,60);
}
this function you can pass the array
Can you try to below one
scroll.contentSize = CGSizeMake(x+size.width+10,20);

UIScrollView needs to get bigger every time I add a button

The scrollView is created in my storyboard and is horizontal. Here is the method where I add a button for every loop and need to increase the size of the scrollView every time a button is added.
- (void) populateGroups {
NSInteger x = [self.groupNameArray count];
for (int i = 0; i < x; i++) {
NSString *name = [self.groupNameArray objectAtIndex:i];
// Create Button
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(count, 0, 100, 54)];
[button setTitle:name forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:10];
[button.layer setBorderWidth:1.0f];
[button.layer setBorderColor:[UIColor whiteColor].CGColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(groupPage:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.groupScrollView addSubview:button];
count = count + 100;
// Increase ScrollViewSize
self.groupScrollView.frame = CGRectMake(0, 0, frameWidth, 80);
frameWidth = frameWidth + 100;
}
}
The scrollView stays the same when I try to add two buttons to the view.
you have to increase the content size of the scroll view like:
self.groupScrollView.contentSize = CGSizeMake(frameWidth, 80);
and better to do it after the loop.

Resources