Dynamic placing of labels and buttons in UIView - iphone

I want to know if there is a dynamic way of populating an UIView.
For example, Consider I have a couple of UILabels aligned as rows, whose text is again dynamic.
If the text for the first UILabel has multiple lines, I know I can call
[myLabel sizeToFit];
to resize itself based on its content.
Is there an easy way of propagating this information to all the subviews (UILabels in my case) of the UIView and making them and respace them accordingly.
I hope I am clear enough.

For two labels that should be aligned as rows, you can use the CGRectGetMaxY function. For example :
UILabel *first = [[UILabel alloc] initWithFrame:CGRectMake(10.0f,20.0f, 100.0f, 200.0f)];
[first setText:#"Text to display"];
[first sizeToFit];
[self.view addSubview:first];
[first release];
UILabel *second = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, CGRectGetMaxY(first.frame), 100.0f, 200.0f];
[second setText:#"Text to display"];
[second sizeToFit];
[self.view addSubview:second];
[second release];
UILabel *third = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, CGRectGetMaxY(second.frame), 100.0f, 200.0f];
[third setText:#"Text to display"];
etc...
You can also know the expected size of a label according to its text parameter doing this :
NSString *text = #"Text to display";
CGSize size = [text sizeWithFont:[UIFont fontWithName:#"HelveticaNeue" size:10.0f] constrainedToSize:CGSizeMake(100.0f, FLT_MAX) lineBreakMode:UILineBreakModeTailTruncation];
UILabel *first = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 20.0f, 100.0f, size.height)];
[first setText:text];

Related

How to set font to ALL of my text field?

I have this code and it's working :
[_fieldEmail setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14]];
[_fieldPassword setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14]];
[_fieldRegisterName setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14]];
[_fieldRegisterEmail setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14]];
[_fieldRegisterPassword setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14]];
[_titleLogin setFont:[UIFont fontWithName:#"Raleway-ExtraLight" size:28]];
[_titleRegister setFont:[UIFont fontWithName:#"Raleway-ExtraLight" size:28]];
[_titleVote setFont:[UIFont fontWithName:#"Raleway-ExtraLight" size:28]];
also I have this code to apply padding left and padding right for each text field that I have :
UIView *fieldEmail = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_fieldEmail.leftViewMode = UITextFieldViewModeAlways;
_fieldEmail.leftView = fieldEmail;
UIView *fieldPassword = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_fieldPassword.leftViewMode = UITextFieldViewModeAlways;
_fieldPassword.leftView = fieldPassword;
UIView *fieldRegisterName = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_fieldRegisterName.leftViewMode = UITextFieldViewModeAlways;
_fieldRegisterName.leftView = fieldRegisterName;
UIView *fieldRegisterEmail = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_fieldRegisterEmail.leftViewMode = UITextFieldViewModeAlways;
_fieldRegisterEmail.leftView = fieldRegisterEmail;
UIView *fieldRegisterPassword = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_fieldRegisterPassword.leftViewMode = UITextFieldViewModeAlways;
_fieldRegisterPassword.leftView = fieldRegisterPassword;
but I think it's an ugly code. because I have to set every text field and label one by one. Is it any better way to simplify this?
thank you very much..
I wouldn't do this way. If you check your code, you have a lot of similar pattern for your TextField.
Why don't create customTextField which is inherited from UITextField? And then, what you need is set font, leftViewMode and leftView in your customTextField class. When use it, just alloc with frame. Done!
In iOS 5 and later you can use the UIAppearance API to give a consistent style to your controls. Which iOS framework are you targeting?
OR
As suggested by Brain you can create a custom TextField and use that instead of UITextField. Your custom TextField would of course inherit from the UITextField but it will change different properties which you desire.
Make two arrays:
NSArray* fields= #[ _fieldEmail, _fieldPassword, _fieldRegisterName, _fieldRegisterEmail, _fieldRegisterPassword ];
NSArray* titles = #[ _titleLogin, _titleRegister, _titleVote ];
Then use makeObjectsPerformSelector:withObject: to execute a method call on all the array objects:
UIFont* font1= [UIFont fontWithName: #"ABeeZee-Regular" size: 14];
UIFont* font2= [UIFont fontWithName:#"Raleway-ExtraLight" size:28];
[fields makeObjectsPerformSelector: #selector(setFont:) withObject: font1];
[titles makeObjectsPerformSelector: #selector(setFont:) withObject: font2];
As for the second task you can simply use iteration and put the created UIView objects in a mutable array, if you need to use them later. If you want call them by name, then also a dictionary is a good idea:
NSArray* keys= #[ #"fieldEmail", #"fieldPassword", #"fieldRegisterName", #"fieldRegisterEmail", "fieldRegisterPassword" ];
NSMutableDictionary* fieldsDict= [[NSMutableDictionary alloc] init];
for(NSString* key in keys) {
UIView* field= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
field.leftViewMode= UITextFieldViewModeAlways;
field.leftView= field; // I hope that this property is weak
[fieldsDict setObject: field forKey: key];
}
You could try to loop through all the subviews and check if they are an instance of UITextField or any subclass of UITextField. If they are, you can set the font property.
I quickly wrote some sample code to show you how you could do this:
for (UIView *subview in [[self view] subviews]) {
if ([subview isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)subview;
[textField setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14.f]];
}
}
Be aware of the fact that this code only loops through the 'closest' children of [self view] and thus won't modify views deeper in the hierarchy.

objective c addSubview order

i am a junior programmer
I face a problem of some of the subview in the program not shown ,
don't know if it is the addsubview order problem or the others .
hope if anyone can provide a suggestion or solution .thanks all
for (int i = 0; i < NUM_DISHES; i++) {
UIImageView* img_steps = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:#"%d.jpg", i]]];
//IMPORTANT: The i*W_IPAD means that 1st 0*1024 , 1*1024 , 2*1024.............and so on
[img_steps setFrame:CGRectMake(W_IPAD, 0, W_IPAD , H_UPFR)];
UIImageView* imageset = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[ary_img objectAtIndex:i]]];
[imageset setFrame:CGRectMake(89, 9, H_INGREPHOTO, W_INGREPHOTO)];
[ary_image addObject:imageset];
//ingredient amount section
UILabel* lbl_amt = [[UILabel alloc] initWithFrame:CGRectMake(128, 177, 190, 33)];
[lbl_amt setText:[ary_amount objectAtIndex:i]];
[lbl_amt setFont:[UIFont systemFontOfSize:25]];
[lbl_amt setTextColor:[UIColor blackColor]];
[lbl_amt setBackgroundColor:[UIColor clearColor]];
[ary_amt addObject:lbl_amt];
//method section
UILabel* lbl_method = [[UILabel alloc] initWithFrame:CGRectMake(596, 93, 130, 32)];
[lbl_method setText:[ary_meth objectAtIndex:i]];
[lbl_method setBackgroundColor:[UIColor clearColor]];
[lbl_method setFont:[UIFont systemFontOfSize:30]];
[lbl_method setTextColor:[UIColor blackColor]];
[ary_method addObject:lbl_method];
//alpha bar step number step number section
UILabel* lbl_numberstep = [[UILabel alloc] initWithFrame:CGRectMake(90 + (130 * i), 5, W_NUMBERSTEP, H_NUMBERSTEP)];
[lbl_numberstep setText:[NSString stringWithFormat:#"%d",i + 1]];
[lbl_numberstep setFont:[UIFont systemFontOfSize:20]];
[lbl_numberstep setBackgroundColor:[UIColor clearColor]];
[lbl_numberstep setTextColor:[UIColor blackColor]];
[self.view addSubview:img_steps];
[alpha_bar addSubview:lbl_numberstep];
[alphaframe addSubview:[ary_method objectAtIndex:i]];
[alphaframe addSubview:[ary_amt objectAtIndex:i]];
[alphaframe addSubview:[ary_image objectAtIndex:i]];
}
// Section --- Add Subview
[self.view addSubview:background];
[background addSubview:main_view];
[main_view addSubview:alpha_bar];
[main_view addSubview:alphaframe];
[main_view addSubview:but_transit_to_a]; //can add to the main_view
[main_view addSubview:left_buttom];
[main_view addSubview:right_buttom];
[alpha_bar addSubview:bar];
[alpha_bar addSubview:lbl_lastnum];
[alphaframe addSubview:but_transit_to_c];
}
return self;
}
To bring the subview to front you can use [yourMainView bringSubviewToFront:yoursubview]. If your subview isn't showing then, check that you've properly set up the subview's frame and that hidden = NO.
The view.subviews array holds the bottom-most view in index zero, and holds views in an order relating to their "z-index". So [myView.subviews lastObject]; will always give the view in front of all other views and [myView.subviews objectAtIndex:0]; will have the view below all views in that array.
From the UIView docs - subviews property:
You can use this property to retrieve the subviews associated with
your custom view hierarchies. The order of the subviews in the array
reflects their visible order on the screen, with the view at index 0
being the backmost view. For complex views declared in UIKit and other
system frameworks, any subviews of the view are generally considered
private and subject to change at any time. Therefore, you should not
attempt to retrieve or modify subviews for these types of
system-supplied views. If you do, your code may break during a future
system update.

Remove label from scrollview

I am creating an iPhone app in which i am using scrollview and adding labels like this :
question = [[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] ;
question.textColor = [UIColor blueColor];
question.text = [NSString stringWithFormat:#"%#" ,selected];
question.lineBreakMode = UILineBreakModeWordWrap;
[question setFont:[UIFont fontWithName:#"Futura" size:30]];
question.backgroundColor = [UIColor clearColor];
question.numberOfLines = 0;
[question sizeToFit];
[self.view addSubview:question];
[scrollview addSubview:question];
now i want to remove this label from scrollview. So how can i do this..??
i am doing this for remove object from main view.
[question removeFromSuperview];
Thanks.
There are some problems in your code. I assume that the scrollview is a subview of self.view. In this case remove the line
[self.view addSubview: question];
from you code. Depending on the rest of your code I would eventually also change the first line. If you don't need to excess the label somewhere else in your code I would change the first line to
UILabel *question = [[UILabel alloc] initWithFrame: CGRectMake(22, 130, 725, 160)];
and add a line after [scrollview addSubview: question]; with
[question release];
This would reduce you memory consumption.
Why are you adding question to the main view and to the scroll view? It doesn't make sense. Remove the [self.view addSubview:question]; line and [question removeFromSuperview]; will remove your label from the scrollview.

TTStyledTextLabel inside UITextView

I have a need to display text that includes HTML tags etc and TTStyledTextLabel fits the bill.....but it does not scroll.
I placed one inside a UITextView but this refuses to scroll? If I enter the text directly in the UITextView it scrolls OK but then I see all the HTML unformatted.
Is there a way to set TTStyledTextLabel to scroll?
Thanks
Try putting the TTStyledTextLabel in a UIScrollView.
Alternately, you can consider using a UIWebView directly.
I finally got a suitable work around...
CGSize constraintSize;
CGSize stringSize;
// make an overly big size allowance
constraintSize.width = 300;
constraintSize.height = 2000;
NSString *s = #"this can be text as long or as short as required...;
UIFont *f = [UIFont fontWithName:#"Arial" size:14];
stringSize =[s sizeWithFont:f constrainedToSize: constraintSize lineBreakMode: UILineBreakModeWordWrap];
// create a label to accomodate the text
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(14, 2, stringSize.width, stringSize.height)];
l.text = s;
[l setNumberOfLines:0];
[l sizeToFit];
// now create a TTStyledTextLabel to match the size we just obtained above
TTStyledTextLabel *tl = [[TTStyledTextLabel alloc] initWithFrame:[l frame]];
// set the text making use of links etc
tl.text = [TTStyledText textFromXHTML:l.text lineBreaks:YES URLs:YES];
[tl setBackgroundColor:[UIColor clearColor]];
tl.textColor = [UIColor whiteColor];
UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 185, 320, 300)];
// adjust scrollview content size to accomodate the TTStyledTextLabel
[sv setContentSize:CGSizeMake(tl.frame.size.width, tl.frame.size.height)];
[sv addSubview:tl];
[self.view addSubview:sv];
Now I can have an auto sizing TTStyledTextLabel that scrolls ;-)

UINavigationBar custom title position

I have a custom made UINavigationBar (different size, background etc) that has inside a custom title view. I used this code to achieve this:
UIView * mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
mainView.backgroundColor = [UIColor yellowColor];
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,0,kScreenWidth,80)];
navBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UINavigationItem *currentItem = [[UINavigationItem alloc] init];
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont fontWithName:#"Helvetica-Bold" size: 30.0];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setText:self.title];
[label sizeToFit];
[currentItem setTitleView:label];
[label release];
[navBar pushNavigationItem:currentItem animated:NO];
[currentItem release];
[mainView addSubview:navBar];
[navBar release];
self.view = mainView;
[mainView release];
However, my problem now is that, even if the custom title view is correctly added, it's not vertically centered with the NavBar. What I am missing?
Thanks!
You can use setTitleVerticalPositionAdjustment:forBarMetrics: in iOS 5 to change the title position, it works on normal title e.g.:
CGFloat verticalOffset = -4;
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:verticalOffset forBarMetrics:UIBarMetricsDefault];
You created you UINavigationBar with a height of 80 points, when a standard UINavigationBar has 44 pts. It probably position it centred it on a 44 pts based centre...
You can try to make a UIView with a height of 80 pts and add the UILabel centred inside it. (not tested, just a guess)