Why is my custom UIView not rendering within the UIView container of it's parent? So what I have is:
MainViewController - has a UIView "customViewContainer" (which doesn't take up the whole screen), and
CustomView - is a UIView with a XIB file - it is the UIView here that when it is rendered (with AspectFit) is rendering outside the bounds of the parent "customViewContainer"
The code used to setup the custom view is this extract from MainViewController:
<< cut - see Update2 below >>
So I can't see why the CustomView view is being rendered in a way that is larger in area than the parent customViewContainer? What I want is for the customview to fit into the parent "customViewContainer" entirely per the AspectFit type approach.
thanks
EDIT 1 (added clarification) - If I "clip subviews" in the parent view then it does then clip things, but what I really need to render the custom view within the parent view area (not the whole area of the screen). So I need (a) the center of the custom view to be in the center of the parent view, and (b) custom view to AspectFit into the parent view properly. Any ideas?
EDIT 2 - Update
sorry - made a copy/paste mistake with code in the original question - can't seem to edit it so I'll put a correct version below - so to clarify:
MainViewController - has a UIView "containerView" (which doesn't take up the whole screen), and CustomView - is a UIView with a XIB file - it is the UIView here that when it is rendered (with AspectFit) is rendering outside the bounds of the parent "containerView"
With the code below does this make sense now? The reason for this code is I have a custom UIView, BUT I have a XIB file associated with it, so this was the only way to get my MainController view to be able to use it. That is, have a container view in the MainController view, and then programmatically add the CustomView into the container view.
Re "So set the frame or center of the view that you're adding to be what you want it to be" - are you saying I have to programmatically/manually set the dimension of the CustomView to be what I want (in relation to the parent containerView)?
What I was hoping was there was a way using the declaritive layout setting to some how be able to say "Load the Custom View from it's XIB file, and the aspectFit this view into the self.containerView", however I'm starting to wonder if this is possible?
UPDATED CODE BELOW (made mistake in original question when I copy/pasted it in and changed variables names etc)
- (void)viewDidLoad
{
[super viewDidLoad];
// Load the custom Altimeter View into this UIControllerView's container UIView for it
NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:#"Customview" owner:self options:nil];
for (NSObject *obj in nibs) {
if ( [obj isKindOfClass:[Customview class]]) {
Customview *cv = (Customview*)obj;
[self.containerView addSubview:cv];
break;
}
}
// UI Layout
self.containerView.layer.borderWidth = 2;
self.containerView.layer.borderColor = [[UIColor redColor] CGColor];
}
Check if the "Clip subviews" property of parent on the IB file is checked.
I think the equivalent code is self.view.clipsToBounds = YES.
if this is NO, subviews that draws outside will be visible as if it's drawn on the parent.
Related
I have a scrollview inside which i have 20 UItextviews. The scrollview is not working. I have set the following in viewdidload.
self.MainScroll.contentSize = CGSizeMake(320, 1800);
Still it doesn't scroll. However, if i give bounce vertically, it just bounces. My scrollview is a child of the main UIview of dimension 320*600. Please guide how to enable the scroll!!
There are two ways you can get the scrolling to work.
Approach 1 (with code):
1) Pin UIScrollView to the sides of its parent view, as mentioned below.
2) Set content size of your scroll view in viewDidLayoutSubviews:
- (void)viewDidLayoutSubviews {
self.MainScroll.contentSize = CGSizeMake(320, 1800);
}
Approach 2 (pure IB, no code required):
1) Setting contentSize is not required if using AutoLayout. You need to pin your UIScrollView to the parent view as mentioned below:
2) Then add another UIView inside UIScrollView to act as a content view and pin it to the UIScrollView and move all controls inside this content view:
3) Pin content view to its parent scroll view as mentioned below:
4) Set your UIViewController's Simulated Metrics to Freeform (this is important):
5) Size your content UIView to your desired height (obviously important too):
Apple article explaining UIScrollView and AutoLayouts:
https://developer.apple.com/library/content/technotes/tn2154/_index.html
Update the content size after some delay as below.
- (void)viewDidLayoutSubviews {
[self performSelector:#selector(updateContentSize)
withObject:nil
afterDelay:0.25];
}
-(void)updateContentSize{
UIView *viewLast = [viewContent viewWithTag:100];
scrollViewAd.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, CGRectGetMaxY(viewLast.frame));
}
So I am using WEPopover to display a custom view controller pop up. I have a UIView in which inside it has another UIView called containerView. Inside this containerView, I have a UIButton. This is where I wanted to present my popover from. So here's what I did:
[self.popoverDialog presentPopoverFromRect:sender.frame inView:self.containerView permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
The issue is that the arrow and everything is showing from this button, but the popover goes out of self.containerView bounds. How can I make it so that the popover is displayed within the containerView bounds?
EDIT:
A picture is worth a thousand words, so here it is:
The light gray is the containerView I mentioned above. THe popover theoretically should be shown within that light gray bounds not going outside.
For the view that is contained inside the popover, go to it's view controller and set it's property contentSizeForViewInPopover. Here you can set the size so that it fits the bounds of your containerView.
OP wants to position the popover so that it only shows up in his container view. I found this bit of code in the WEPopoverController.m file
- (void)repositionPopoverFromRect:(CGRect)rect
inView:(UIView *)theView
permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections {
CGRect displayArea = [self displayAreaForView:theView];
WEPopoverContainerView *containerView = (WEPopoverContainerView *)self.view;
[containerView updatePositionWithAnchorRect:rect
displayArea:displayArea
permittedArrowDirections:arrowDirections];
popoverArrowDirection = containerView.arrowDirection;
containerView.frame = [theView convertRect:containerView.frame toView:backgroundView];
}
You could possibly call this method and it might reposition your popover so that it is now inside your container viw.
I am new to iPad developer,
I made one Registration form in my application, when i see my application in Portrait mode,
i am able to see whole form with no scrolling, but when i see same form in Landscape mode, i am not able to see part which is at bottom of page, for that a scrolling should be there to see bottom part.
:
In my .h file when i replace
#interface ReminderPage : UIViewController{
...
...
}
:UIViewController with :UIScrollView
and then when i add label in my .m file like this,
UILabel *Lastpaidlbl = [[[UILabel alloc] initWithFrame:CGRectMake(70 ,400, 130, 50)]autorelease];
Lastpaidlbl.backgroundColor = [UIColor greenColor];
Lastpaidlbl.font=[UIFont systemFontOfSize:20];
Lastpaidlbl.text = #"Lastpaid on :";
[self.view addSubview:Lastpaidlbl];
I am getting error on last line Property view not found on object of type classname.
i am unable to add label in my view.
Any help will be appreciated.
The question appears to be really asking how can all the components on the screen be placed inside a UIScrollView, rather than a UIView. Using Xcode 4.6.3, I found I could achieve this by simply:
In Interface Builder, select all the sub-views inside the main UIView.
Choose Xcode menu item "Editor | Embed In | Scroll View".
The end result was a new scroll view embedded in the existing main UIView, will all the former sub-views of the UIView now as sub-views of the UIScrollView, with the same positioning.
If you want to replace your UIViewController with a UIScrollView, you will have to go a bit of refactoring to your code. The error you get is just an example of that:
the syntax:
[self.view addSubview:Lastpaidlbl];
is correct if self is a UIViewController; since you changed it to be UIScrollView, you should now do:
[self addSubview:Lastpaidlbl];
You will have quite a few changes like this one to make to your code and will face some issues.
Another approach would be this:
instantiate a UIScrollView (not derive from it);
add your UIView (such as you have defined it) to the scroll view;
define the contentSize of the scroll view so to include the whole UIView you have.
The scroll view acts as a container for your existing view (you add your controls to the scroll view, then add the scroll view to self.view); this way, you could integrate it within your existing controller:
1. UIScrollView* scrollView = <alloc/init>
2. [self.view addSubview:scrollView]; (in your controller)
3. [scrollView addSubview:<label>]; (for all of your labels and fields).
4. scrollView.contentSize = xxx;
I think the latter approach will be much easier.
Please put all of your UIComponents to the UIScrollview and then it will start scrolling.
please look in to content size. please change it according to the orientation of device.
You're subclassing UIScrollView, so there is no self.view because already self is the view (of the scrollview). You dont need to subclass the scrollview, you can just embed your components in a ivar scrollview and set its contentSize (in your case, you have to enable the scrolling just when the device is in landscape mode). In interface builder you can embed the selected elements in one click, Editor-> Embed in-> scrollview.
First create scrollview
UIScrollView * scr=[[UIScrollView alloc] initWithFrame:CGRectMake(10, 70, 756, 1000)];
scr.backgroundColor=[UIColor clearColor];
[ self.view addSubview:scr];
second
change [self.view addSubview:Lastpaidlbl];
to
[scr addSubview:Lastpaidlbl];
third
set height depends on content
UIView *view = nil;
NSArray *subviews = [scr subviews];
CGFloat curXLoc = 0;
for (view in subviews)
{
CGRect frame = view.frame;
curXLoc += (frame.size.height);
}
// set the content size so it can be scrollable
[scr setContentSize:CGSizeMake(756, curXLoc)];
Finally
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Override to allow orientations other than the default portrait orientation.
if (interfaceOrientation==UIInterfaceOrientationLandscapeLeft || interfaceOrientation==UIInterfaceOrientationLandscapeRight) {
self.scr.frame = CGRectMake(0, 0, 703,768);
} else {
self.scr.frame = CGRectMake(0, 0, 768, 1024);
}
return YES;
}
I'm about to add a UIScrollView to my iPhone project and before I implement this functionality I wanted to check if my approach is the right one or if I could be violating some best practice I'm not aware of.
The tutorials I've seen generally involve adding a UIScrollView to an existing UIView and they work from there. However, I was wondering if I could spare the UIView altogether and just add the UIScrollView as the only top-level object in my nib file.
My sample project uses Xcode's View-based Application template:
Project navigator http://img542.imageshack.us/img542/5364/projectnavigator.png
I deleted the UIView top-level object from the original MySampleViewController.xib file and replaced it by adding a UIScrollView object:
Nib placeholders http://img526.imageshack.us/img526/7709/placeholderobjects.png
Now my nib file only shows this object in the canvas:
Canvas http://img233.imageshack.us/img233/4063/scrollview.png
Then I created the link from the UIViewController's view outlet to the UIScrollView.
Now, if I wanted to programmatically manipulate the contents of the UIScrollView I can use this code:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
// Solution B: With the following line we avoid creating an extra outlet linking to the UIScrollView top-level object in the nib file
UIScrollView *scrollView = (UIScrollView *)self.view;
for (int i = 0; i < colors.count; i++) {
CGRect frame;
//frame.origin.x = self.scroller.frame.size.width * i; // Solution A: scroller is an IBOutlet UIScrollView *scroller;
frame.origin.x = scrollView.frame.size.width * i; // Solution B
frame.origin.y = 0;
//frame.size = self.scroller.frame.size; // Solution A
frame.size = scrollView.frame.size; // Solution B
UIView *subView = [[UIView alloc] initWithFrame:frame];
subView.backgroundColor = [colors objectAtIndex:i];
//[self.scroller addSubview:subView]; // Solution A
[self.view addSubview:subView]; // Solution B
[subView release];
}
//self.scroller.contentSize = CGSizeMake(self.scroller.frame.size.width * colors.count, self.scroller.frame.size.height); // Solution A
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * colors.count, scrollView.frame.size.height); // Solution B
}
In order to implement Solution A the scroller outlet must be linked to the nib's UIScrollView as well, and the Connections Inspector looks like this:
Connections Inspector http://img228.imageshack.us/img228/8397/connectionsj.png
Solution A requires an outlet and this means having two connections to the UIScrollView: the UIViewController's own view outlet and MySampleViewController's scroller outlet. Is it legal and/or recommended to have two outlets pointing to the same view?
Solution B only involves UIViewController's view outlet linking to the view, and using this line:
UIScrollView *scrollView = (UIScrollView *)self.view;
My questions:
Do I incur in some sort of violation of Apple's design guidelines by using one of these two solutions?
Should I stick to the UIScrollView within a UIView solution?
Is there any other way to implement this?
Thanks!
P.S. Sorry for the syntax highlight, SO didn't recognize the use of the 'objective-c' tag
No I think you are fine either way.
I would, I don't think a UIView has any significant cost, plus what if you want to add a page control? and you don't have to cast the controller's view to a UIScrollView every time you need it.
Looks like you have it under control to me.
Solution A requires an outlet and this means having two connections to the UIScrollView: the UIViewController's own view outlet and MySampleViewController's scroller outlet. Is it legal and/or recommended to have two outlets pointing to the same view?
It standard to have IBOutlets to any view defined in your .nib that you want to access directly from your view controller.
If you don't want two outlets you could give the scroll view a tag then find it like so:
UIScrollView *myScrollView = (UIScrollView *)[self.view viewWithTag:1]
Then you only have the view as an outlet, but I would just add the extra outlet. Just make sure you set them to nil in your viewDidUnload.
Also you don't have to retain the scroll view (if you are even still using retain/release). Since the scroll view is inside your view controller's view it keeps a reference so you can have your scrollview's property by assign or week if your using ARC.
Hope that helps.
I'm designing using IB a specific button (with some labels,and imageView and other stuff).
I would like then to use that xib object (the button) in another xib, where I have 6 objects of that button.
I know I can do that programmatically using the Class Identifier, but then I have to position my lables and image view, and set the default values and everything else in code.
I'm wondering if it's possible to do the same thing using just the IB ? (of course I would still set the values in code, but I want to positions of the lables/imageView and all the rest to be set in the xib)
Thanks
Edit
So, I understand what I asked for at first is not possible.
What I'm trying now is like that :
I created a ButtonTest.xib.
Inside the Xib I have a UIView and 3 subviews (2 lables and a button).
In the inspector I set the UIView class to ButtonTest.
Inside ButtonTest.m I have 3 outlets for each of the subviews, which I connect in IB.
Next I have a ButtonTestViewController.xib.
Inside it I put one view and set it's class in the inspector to be ButtonTest.
I connect that view to a myTextView outlet inside ButtonTestViewController.m of class ButtonTest
Now, this is the code inside ButtonTestViewController.m viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:#"ButtonTest" owner:nil options:nil];
ButtonTest *mainView = (ButtonTest*)[subviewArray objectAtIndex:0];
self.myTextView = mainView;
}
What I hoped would happen, is that the view in ButtonTestViewController.xib would become the view I designed in ButtonTest.xib.
This just isn't happening. what happens is that the view inside ButtonTestViewController.xib stays the same.
Worth mentioning, is that if I add:
[self.view addSubview:mainView];
It does add the new view, besides the existing one.
Any idea how to do what I want ?
Eventually I would like to have 6 views in ButtonTestViewController.xib, all would look like the ButtonTest.xib template, and the lables values will be set in code.
Edit2
Ok, guys I did everything you said and it worked like a charm.
The only problem I have right now with this issue is when the view in ButtonTestViewController.xib is a little bigger then view in ButtonTest.xib.
When that happens, The lable on the button look extremely blurry.
When they are both the same size, it's all good.
# Ned - I used the exact code you posted in my InitWithCoder method, except I switched the frame sentence to this :
self.bounds = mainView.frame;
I tried playing with the content mode in IB trying to fix it, to no avail.
When I do use it like you posted, meaning :
mainView.frame = self.bounds;
It's not working at all, and both views' sizes stay the same.
Here I tried playing with the resizeMask but still didn't work.
And idea how to fix these 2 issues ?
Thanks guys!
Edit 3
I did manage to fix one of the issues, resizing the ButtonTestViewController.xib to the ButtonTest.xib view size.
This is what I did (using code to solve the blurry issue, taken from here)
self.bounds = CGRectMake(0, 0, mainView.frame.size.width, mainView.frame.size.height);
CGRect overlay2Frame = self.frame;
overlay2Frame.origin.x = round(overlay2Frame.origin.x);
overlay2Frame.origin.y = round(overlay2Frame.origin.y);
self.frame = overlay2Frame;
The other issue I still can't solve. the view in ButtonTest.xib just won't get bigger to match the other view.
You can do this, and pretty easily. The way I do this is create a UIView subclass (let's say it's called "MyView.m" and "MyView.h"), and then a nib called "MyView.xib".
First, in the nib, click File's Owner, and set the class to "MyView". This will make it so IBOutlets/Actions from your class show up in IB. Add a single top-level view (if it doesn't have one already) as your main view, and add your other custom elements (UILabels and UIImageViews) as subviews of the main UIView.
Next, add the following code so that it gets called when MyView is initialized (remember, if you initialize from a nib it'll get initialized via - (id)initWithCoder:(NSCoder *)aDecoder).
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
//Just in case the size is different (you may or may not want this)
mainView.frame = self.bounds;
[self addSubview:mainView];
What this does is loads the view hierarchy from your nib into the NSArray, and since you only had one top-level UIView, you just add that as a subview of your custom UIView.
This allows you to design UIViews (and other subclasses of UIView) in Interface Builder.
EDIT: Updated to OP's edit.
The way I've always done this is by first following my directions above. One difference is that in your ButtonTest nib you're changing the class of the UIView to ButtonTest, but I change the File Owner's class to ButtonTest. Then, inside ButtonTest.m, do the loadNibNamed stuff. Now, to add that object to ButtonTestViewController.xib, add a UIView (or UIButton, whatever ButtonTest is subclassed from) and change the class to ButtonTest.
This is a little confusing, so I'll try to break it up by file.
ButtonTestViewController.xib: Add a UIButton (of whatever ButtonTest inherits from) and change the class to ButtonTest
ButtonTest.m: Inside the "initWithCoder" method, do all of the "loadNibNamed" stuff I have above
ButtonTest.xib: Change File's Owner class to ButtonTest and link up all IBOutlets and IBActions
Some of you ask in comment if this solution doesn't create infinite loop and I don't have enough reputation to answer there, so here is my answer:
The loop exist if root view in your XIB has "Custom class" set to MyView. This causes the situation where view loaded from XIB invokes initializer of MyView again and therefore, creates infinite loop. The solution is that "Custom class" should be UIView and only File Owner's class should be set to MyView (to be able to assign IBOutlets and IBActions).
Swift 3.0
create swift file with class
class ViewXIBfileClassView: UIView {
.....
}
create Xib file with view:ViewXIBfileClassView
create wrapper view class
class ViewWrapper: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let view = UINib(nibName: "ViewXIBfileClassView_file", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! viewXIBfileClassView
self.addSubview(view)
view.bindEdgesToSuperview()
}
}
add extension to UIView
extension UIView {
/// Adds constraints to the superview so that this view has same size and position.
/// Note: This fails the build if the `superview` is `nil` – add it as a subview before calling this.
func bindEdgesToSuperview() {
guard let superview = superview else {
preconditionFailure("`superview` was nil – call `addSubview(view: UIView)` before calling `bindEdgesToSuperview()` to fix this.")
}
translatesAutoresizingMaskIntoConstraints = false
["H:|-0-[subview]-0-|", "V:|-0-[subview]-0-|"].forEach { visualFormat in
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: visualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
}
}
}
Use UIView with ViewWrapper inside all Xib files you want
If your class is a subclass of UIButton for example, you can open the Library in Interface Builder and it will be under the classes tab when you search for it and you can drag and drop.
You can also just drag/drop a UIButton and set its class in the inspector pane.
However, because you have your own .xib that might mess it up, in which case just ignore me.