Dynamic View Controller - ios

I just need to find out several things about iOS views and layout. I have just ended application where I had to create a controller that show test. It was easy except one thing. There was two types of question A and B. A questions have 4 variants of answers, B questions don't. So I had to generate all my layout in code depends on question type. I've done it by creating method update where i rebuild my views.
- (void)update {
for (UIView *v in self.view.subviews) {
[v removeFromSuperview];
}
//label initialization with frame calculation
UILabel *questionLabel = [[UILabel alloc]initWithFrame:CGRectMake(PADDING, PADDING, size.width - 4 * PADDING, 0)];
[questionLabel sizeToFit];
[self.view addSubview:questionContainerView];
//If type A
if ([self.question.questionType isEqualToString:#"A"]) {
for (Answer *a in self.question.answers) {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(PADDING, offset, size.width - 2 * PADDING, 30 + PADDING)];
//customization
[self.view addSubview:button];
offset += button.frame.size.height + MARGIN_BOTTOM;
}
//if B type
} else {
UITextField *answerField = [[UITextField alloc] initWithFrame:CGRectMake(PADDING, PADDING, view.frame.size.width - 2*PADDING, view.frame.size.height - 2 * PADDING)];
[view addSubview:answerField];
offset += view.frame.size.height + MARGIN_BOTTOM;
}
UIView *lastView = [[self.view subviews]lastObject];
self.scrollView.contentSize = CGSizeMake(size.width, lastView.frame.origin.y + lastView.frame.size.height + 10);
}
And after all I think it's can't be so sophisticated. Please help to find out how should I do it properly, because I am sure my method is not optimal. Maybe create custom layout. I mean how to avoid setting frame and simply add views which take right position.

This is extremely vague and I am assuming you are against using any GUI tools? Regardless, rather than creating each view after each update why not just create both views then hide or show them depending on the question?
You can do this simply using bringSubviewToFront or sendSubviewToBack or simply setHidden. That way you can create your views and simply show or hide them without destroying them and recreating everything although something this simple can easily be done that way.
My advice? Create these subviews using a storyboard or Xib then simply hide or show the view of your choice. That way you can easily layout the views however you like without touching any code.
Now, if the questions all change constantly than this is the EXACT place you would want to use a UITableViewController as this is what it's designed for. You can create a few custom UITableViewCells for your different question scenarios then reuse them depending on the type of questions. Then you simply update your dataSource for the tableView and all of your new questions appear how you like.

Related

Objective-C: add subview only work for one view

For each UIImageView, I want to add the label subview to it.
Here is my class inherited form UIImageView
-(instancetype)initWithFrame:(CGRect)frame
{
if (self=[super initWithFrame:frame]) {
self.categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 50)];
self.categoryLabel.textAlignment=NSTextAlignmentCenter;
self.categoryLabel.font=[UIFont systemFontOfSize:20];
self.categoryLabel.textColor=[UIColor whiteColor];
[self addSubview:self.categoryLabel];
NSLog(#"%#",self.subviews);
}
return self;
}
-(void)setModel:(HorizontalModel *)model
{
_model=model;
self.categoryLabel.text=self.model.category;
[self sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"XXXXX%#",self.model.imgURL]] placeholderImage:[UIImage imageNamed:#"obama"]];
}
Here is my code in the view controller.
-(void)addImage:(NSNotification *)notification
{
self.HArrayLists=notification.userInfo[#"array"];
for (int i=0; i<[self.HArrayLists count]; i++) {
JTImageView *imageView=[[JTImageView alloc] initWithFrame:CGRectMake(i*310, 0, 300, 200)];
imageView.model=[HorizontalModel restaurantsDetailWithDict: self.HArrayLists[i]];
[self.mediaScrollView addSubview:imageView];
}
self.mediaScrollView.contentSize=CGSizeMake(310*[self.HArrayLists count], 0);
}
It turns out that only the first imageView shows a label, while the rest of the imageViews show only images.
I think the core of your problem is the line:
self.categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 50)];
You are offsetting the x and y positions of the label by the x and y values of the image. This will place them outside the area of the image and with the image clipping, make them invisible. I think the line should be
self.categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, 50)];
to place all the labels at the top left corner of each image.
Having said that there are also a number of recommendations I would like to offer.
Firstly make all variable names start with a lowercase. So self.HArrayLists should be self.hArrayLists.
Secondly try and make variable names match their contents. So again looking at self.HArrayLists, perhaps something like self.imageData.
Next I would have done the composition differently. I would have a UIView to which I add both the UILabel and UIImageView instances. Using a parent view like this to layout two sub views often makes life easier.
I would also look into using a UICollectionView and UICollectionViewController rather than a UIScrollView. It will take you a bit of work to get your heads around how collection views work. But you will gain in terms of performance and better layout management.
Finally, study up on constraints. They're an essential part of building modern apps that can easily adapt to different sized screens, rotation and layouts.
You need to set as categoryLabel's frame properly.
self.categoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, frame.origin.y, frame.size.width, 50)];

Adding Images By incrementing label count

Here,when button taps label count is increments & decrements.While label count increments images will be added by respective count.here my code for incrementing label count
if (counter >= 9 )
return;
[_count setText:[NSString stringWithFormat:#"%d",++counter]];
but i need to display while incrementing the label count then automatically increments images one by one.like this
Can you please help me how can i implement,thank you.
Add a UIScrollView in place of where you want to show images. When click on '+' button, call following method by passing the 'counter' value.
-(void)addImage:(int) count {
UIScrollView * scView = [[UIScrollView alloc] init];
scView.frame = CGRectMake(30, 60, self.view.frame.size.width, 60);
UIButton * btn;
UIImageView * imgV;
float imgWidth = 44;
for(int i=0;i<count;i++) {
imgV = [[UIImageView alloc] init];
imgV.frame = CGRectMake(i*imgWidth, 0, imgWidth, 44);
imgV.image = [UIImage imageNamed:#"gitar"];
[scView addSubview:imgV];
}
[scView setContentSize:CGSizeMake(imgWidth*count, 50)];
[scView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:scView];
}
- (IBAction)descrese:(id)sender {
counter -= 1;
[self addImage:counter];
}
- (IBAction)btnTap:(id)sender {
counter += 1;
[self addImage:counter];
}
This adds as many images as you want in horizontal scroll view.
use a uiscrollview with cells of images, that simple.
Use UIScrollView.
As number of elements is increasing/decreasing:
1) increse/deacrease UIScrollView size respectively
2) add/remove elements
I guess, the screenshot was taken from MMT app. They're using this feature in their app. I believe, they might have developed a separate control to handle this thing, where they can only pass few arguments like image to show (people), count etc.
You can also develop such kind of UI with following way:
Create a custom view, take a UICollectionView inside it, take argument of image to show and number of rows count, fixed the cell size in layouts. Add a method which will reloads UI (inside logic: reloading UICollectionView) to refresh content when user taps on [ + ] or [ - ] button. Why, we're not taking UIScrollView, with it we can't reuse contents. I believe this step will need you to create everything programmatically.
When user taps on [ + ], you should increase width of our custom view, inside
you should override layoutSubview method to update frame of UICollectionView as well. You may require to refresh(reload) cells inside UICollectionView.
Do reverse when user taps [ - ].
You may require to set some logic so user can't add more/less numbers when selection.
This is just an idea, you may require to check each cases which the reference app has having.

Why viewDidLayout only got called once on iOS 7, but several times on iOS 8

I have an project using autolayout,
And I notice that after viewWillAppear, viewWillLayoutSubViews and viewDidLayoutSubViews pair will be called several times on iOS 8, for my case, it is 2-3 times usually.
The fist viewDidLayoutSubViews will get incorrect frame size, so I have to avoid for first viewDidLayoutSubViews, and init my views afterwards.
However, when I tested it on iOS 7, I found that only ONE viewWillLayoutSubViews and viewDidLayoutSubViews pair got called, so my code broke again.
My question is, what is changed on iOS 8 for this behaviour?
EDIT:
I have pasted my demo code here:
In the code, _pieChart will be added to self.ChartViewCanvas, and self.ChartViewCanvas is using autolayout. _pieChart is from old project code, which is drawn without auto layout.
I was required to draw the pie chart before viewDidAppear, because drawing in viewDidAppear will have a 1 sec delay compare to other views in storyboard. This is not allowed for me.
Is there any way to know when is the final viewDidLayoutSubViews? Calling [self.ChartViewCanvas addSubview:_pieChart]; multiple times will lead to lower performance, and sometimes _pieChart's drawInRect will not be called every time, so the chart is not update.
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
_pieChart.delegate = self;
if (!_pieChart) {
_pieChart = [[PieChartView alloc] initWithFrame:CGRectMake(0, 0, pieRadius * 2, pieRadius * 2)];
}else {
[_pieChart setFrame:CGRectMake(0, 0, pieRadius * 2, pieRadius * 2)];
}
//_pieChart.translatesAutoresizingMaskIntoConstraints = NO;
if ([_pieChart superview]) {
[_pieChart removeFromSuperview];
}
[self.ChartViewCanvas addSubview:_pieChart];
}
Probably only Apple knows, but I won't deal with that too much if everything is working fine. In iOS8 Apple changed a lot view controllers (again) in they way they are presented from containers VC as for rotation and UITraitCollections.
For instance UIAlertView is now a view controller, when you show one you trigger all the mechanism related to present a VC.
If this fact is creating an issue it must be said that you should not rely on how many times those methods are called because they were always be unpredictable there are too many variables to be taken into account.
A quick and dirty solution could be wrap your code in a dispatch_once if you want that it will be called only one time.
If you add your view using auto layout correctly you won't see any sort of bug.
[EDIT]
Here is a little snippet about how it might look your viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
//.. your stuff
//We don't need any frame autolayout wil take care of calculating it on its pass
_pieChart = [[PieChartView alloc]initWithFrame:CGRectZero];
_pieChart.delegate = self;
_pieChart.translatesAutoresizingMaskIntoConstraints = NO;
[self.ChartViewCanvas addSubview:_pieChart];
NSDictionary *bindings = NSDictionaryOfVariableBindings(_pieChart);
// We create constraints to tell the view that it needs to sctretch its bounds to the superview
NSString *formatTemplate = #"%#:|[_pieChart]|";
for (NSString * axis in #[#"H",#"V"]) {
NSString * format = [NSString stringWithFormat:formatTemplate,axis];
NSArray * constraints = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:nil views:bindings];
[_pieChart.superview addConstraints:constraints];
}
// Do any additional setup after loading the view.
}
Of course that is going to call drawRect:, draw rect is called when a view is marked as dirty in the display pass, but before display is usually called the autolayout engine to calculate frames of views in needs for layout.
I tried this out on my application and found the same as you: 1 call on iOS7 and 3 on iOS8. From the stack traces this seems to be down to doing double layout after viewWillAppear and an extra layout following viewDidAppear not seen on iOS7.
My suggestion would be that you add any views in viewDidLoad (or viewWillAppear), then only do layout adjustments in the layout subview runs. Based on your updated post something like:
- (void)viewDidLoad{
[super viewDidLoad];
_pieChart = [[PieChartView alloc] initWithFrame:CGRectMake(0, 0, pieRadius * 2, pieRadius * 2)];
[self.ChartViewCanvas addSubview:_pieChart];
_pieChart.delegate = self;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[_pieChart setFrame:CGRectMake(0, 0, pieRadius * 2, pieRadius * 2)];
}
For interest the difference between iOS7 and 8 calling sequence was:
iOS7
i) viewWillAppear is called.
ii) layout of subviews is called. From the stack this seems to relate to the navigation bar and animation.
ii) viewDidAppear is called.
iOS8
i) viewWillAppear is called.
ii) layout of subviews is called. From the stack this seems to relate to the navigation bar and animation.
iii) exact same layout with exact same stack is called again. So something in the stack must request a rerun from some point.
iv) viewDidAppear is called.
v) An extra layout of subviews is called. This seems driven from a transaction pushed onto the run loop.

UISearchBar - internal UITextField height issue

I'm working on an app where I place a UISearchBar at the top of a UIViewController that contains a UITableViewController. The UISearchBar filters the contents of the UITableView.
I've left things alone so far (aside from customizing the colors to match my app's theme, which was hard enough!), but on anything except iPhone 4/5, the UISearchBar is dramatically too small.
Therefore, I'm trying to update the size of the font and the height of the internal UITextField.
All of this has proved remarkably difficult to accomplish, requiring quite a bit of customization. So, if you know of a library that makes this easier, please let me know in the comments.
Here's the code I'm using right now:
// In a category for UISearchBar
- (void)setup {
self.tintColor = [UIColor offWhite];
for (UIView *view in self.subviews) {
[self configureView:view];
}
}
- (void)configureView:(UIView *)view {
if ([view isKindOfClass:[UITextField class]]) {
CGFloat fontSize, frameHeight;
if (IS_IPHONE_4) {
fontSize = 14.0f;
frameHeight = 24.0f;
} else if (IS_IPHONE_5) {
fontSize = 14.0f;
frameHeight = 24.0f;
} else if (IS_IPHONE_6) {
fontSize = 17.0f;
frameHeight = 28.0f;
} else if (IS_IPHONE_6PLUS) {
fontSize = 20.0f;
frameHeight = 32.0f;
} else {
// iPad
fontSize = 24.0f;
frameHeight = 36.0f;
}
UITextField *textfield = (UITextField *)view;
textfield.font = [UIFont buttonFontOfSize:fontSize];
textfield.textColor = [UIColor offWhite];
textfield.tintColor = [UIColor offWhite];
CGRect frame = textfield.frame;
frame.origin.y = (self.frame.size.height - frameHeight) / 2.0f;
frame.size.height = frameHeight;
textfield.frame = frame;
}
if (view.subviews.count > 0) {
for (UIView *subview in view.subviews) {
[self configureView:subview];
}
}
}
Note: I structured my code this way in case Apple changes the internal structure of the UISearchBar. I didn't want to hard-code index values.
So, this code "works", in that the end result is what I desire, namely, a taller UISearchBar with text sized as specified and the internal UITextField also taller, as specified. What I don't understand is the process of getting there.
If I call [self.searchBar setup] in my general AutoLayout process, it doesn't work (the internal UITextField is the wrong height). This makes sense to me, since the frame is (0,0,0,0) until the view is actually laid out.
If I call [self.searchBar setup] in my -viewWillAppear: method, it doesn't work (the internal UITextField is the wrong height). This doesn't make sense to me, since debugging shows the frames to still be (0,0,0,0), but I thought -viewWillAppear: was called when everything was laid out and set up.
If I call [self.searchBar setup] in my -viewDidLayoutSubviews method, it "works", but the internal UITextField starts out the "normal" height and then "jumps" to the correct height some time after the view actually appears.
I set up the entire UIViewController in code, using pure AutoLayout. I simply cannot get the UISearchBar set up the way I want BEFORE the view finished loading and is displayed on screen. I've seen some funky stuff in the past, but I've always been able to force a view to render as desired. Is there something special behind the scenes with UISearchBar? Does anybody know how to get this done?
You're mixing auto-layout and manual layout (someView.frame = …) on the same view. You can't do that.
Instead, to change the height, set the constant on your view's height constraint to frameHeight. Let the auto-layout engine set the frame for you.

How do I hide controls and cause others to shift place in iOS?

I'm programming an app for iOS 7 in Xcode 5.
I have three text boxes at the top of my page, each right above the other. Let's call them topTextBox, middleTextBox, and bottomTextBox.
My intent is that depending on a particular condition, the topTextBox might not be visible (or present, really) when the view loads.
If topTextBox isn't present (or hidden, or whatever) I would like middleTextBox and bottomTextBox to be placed further up the page...as if topTextBox wasn't ever there in the first place (so middleTextBox is in the spot topTextBox used to be in, and bottomTextBox is in the spot middleTextBox was in).
I'm using storyboards with AutoLayout ON. I can't seem to figure out what to do with the constraints for each of the three textBoxes to make this work. Making middleTextBox and bottomTextBox sit higher on the page when topTextBox is hidden doesn't need to be dynamic--I make the decision to show or not show topTextBox in ViewDidLoad()--I just need to get them to show up in the right place depending on my conditions.
Questions:
a. Is making topTextBox.hidden = YES the right way to get topTextBox to not be shown? Or is there some way to make it not noticed by the view at all?
b. What do I do with these constraints on middleTextBox and bottomTextBox to move them up on the page in this condition?
c. Is there anything else I should know to get this to work that I'm not thinking of? Perhaps a better method?
Thanks.
Have you tried just hard coding the frame logic? This could be very effective. All you have to do is conditionally populate an array containing pointers to your text fields and then perform a little frame arithmetic on their y origins. For example, this could easily display all the fields:
NSArray *fields = #[topTextField, middleTextField, bottomTextField];
for (int i = 0 ; i < fields.count ; i ++) {
UITextField *field = fields[i];
[field setFrame:CGRectMake(20.0, 20.0 + (i * 50.0), 280.0, 34.0)];
}
Produces this:
Or at its most basic level, something like this could be used to check whether any of the text fields should/shouldn't be shown, and either hides them, or adjusts their frame accordingly.
BOOL shouldShowTop = YES;
BOOL shouldShowMiddle = NO;
BOOL shouldShowBottom = YES;
NSMutableArray *fields = [NSMutableArray new];
if (shouldShowTop) {
[fields addObject:topTextField];
}else{
[topTextField setHidden:YES];
}
if (shouldShowMiddle) {
[fields addObject:middleTextField];
}else{
[middleTextField setHidden:YES];
}
if (shouldShowBottom) {
[fields addObject:bottomTextField];
}else{
[bottomTextField setHidden:YES];
}
for (int i = 0 ; i < fields.count ; i ++) {
UITextField *field = fields[i];
[field setFrame:CGRectMake(20.0, 20.0 + (i * 50.0), 280.0, 34.0)];
}
Will produce this:
Setting the height constraint of topTextField to 0 will help you to achieve this.
provided all textfields are connected through vertical space constraint
Setting the height of topTextField so that it has zero height could also work for you.
CGRect frame = topTextField.frame;
frame.size.height =0;
topTextField.frame = frame;
This is a good choice should you want to animate its re-appearance later on.
As for constraints, constrain the top of the topTextField to the superview, and then the top of middleTextField and bottomTextField to the bottom of the textfield above.
Do not set a constraint for the height of topTextField, but do set width constraints. You'll need to set the height of topTextField in viewDidLoad:

Resources