firstly I want to say that I am newbie at iOS development. I have a problem with showing a view from xib file in ScrollView.
This MyView is only green background with one label. Here is a code from its controller:
#implementation MyView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//init code
}
return self;
}
- (id) initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
[self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
}
return self;
}
#end
And here is a code from main controller where is the ScrollView:
- (void)viewDidLoad
{
[super viewDidLoad];
scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 67, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
scroll.frame = CGRectMake(0, 20, 320, 350);
scroll.contentSize = CGSizeMake(320, 350);
scroll.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
scroll.bounces = YES;
scroll.bouncesZoom = YES;
scroll.scrollEnabled = YES;
scroll.minimumZoomScale = 0.5;
scroll.maximumZoomScale = 5.0;
scroll.delegate = self;
scroll.pagingEnabled = YES;
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:#"MyView" owner:self options:nil];
UIView *myView = [nibContents objectAtIndex:0];
myView.frame = CGRectMake(0,20,300,300);
[scroll addSubview:myView];
}
Only thing I want to do is that I want to see MyView (green background with one label) inside the ScrollView. If I run this app, scrollview is empty, nothing is shown inside.
Probably it is a stupid question but as I said, I am newbie at this. I have a PageControll app from Apple but for me this is quite complicated code in my iOS beginning. Of course I was googling... Please tell me where is a problem. Thank you
Where do you define scroll? Is it a property of your viewcontroller?
I think the problem here is that you don't add scroll view to your viewcontroller's view with
[self.view addSubview:scroll]
Everything seems to right. Just retain the view in your class that you are receiving from the following line and add that as a subview to your scrollview.
self.myView = [nibContents objectAtIndex:0];
Best Regards.
Related
I asked here (UIView added as an UIWindow subview doesn't respond to taps) but I thought it deserved its own question.
If I set up a subclassed UIView (CustomView) this way, I can't get gestures to work within the view:
CustomView *customView = [[[CustomView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame];
customView.frame = [UIApplication sharedApplication].keyWindow.bounds; // leaves space at bottom of screen if not here
[[UIApplication sharedApplication].keyWindow addSubview:customView];
But if I set up this way, gestures work fine:
CustomView *customView = [[[CustomView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame];
customView.frame = [UIApplication sharedApplication].keyWindow.bounds; // leaves space at bottom of screen if not here
[[UIApplication sharedApplication].windows[0] addSubview:customView];
Note that using .windows[0] instead of .keyWindow means the status bar is still there, so I have to hide that when I unhide customView to get an empty full screen.
Within customView:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
id mainView;
if (self)
{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:#"CustomNib" owner:self options:nil];
mainView = [subviewArray objectAtIndex:0];
}
return mainView;
}
And here's the gesture setup, also within customView:
UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
[self addGestureRecognizer:singleFingerTap];
Any ideas why the gesture recognizer doesn't work when the view is a subview of .keyWindow but works when the view is a subview of .windows[0]?
In initWithFrame, you are returning a UIView --- not an instance of CustomView.
You probably want your CustomView code to look like this:
#import "CustomView.h"
#implementation CustomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
UIView *mainView;
if (self)
{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:#"CustomNib" owner:self options:nil];
mainView = [subviewArray objectAtIndex:0];
mainView.frame = self.bounds;
mainView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:mainView];
[self setupTap];
}
return self;
}
- (void) setupTap {
UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
[self addGestureRecognizer:singleFingerTap];
}
- (void)handleTap:(UIGestureRecognizer *)g {
NSLog(#"Tap in CustomView!");
}
#end
I am sublassing either an UIImageView or UIView for generating simple color tiles with digits. If I am using UIImageView, I use initWithImage method. If I use UIView, the method initWithFrame is being used.
Either red square image or programmatically generated red view is used for initialization.
The problem can be seen on two screenshots: when initWithImage is being used - everything works fine. If initWithFrame method is being used, I am ending with multiple white views without any information created in even order with normal views. All the screenshots and code attached.
This how it looks when initializing using initWithImage:
- (id)initWithImage:(UIImage *)image {
self = [super initWithImage:image];
if (self) {
//Some non-important, label-related stuff.
[self addSubview:self.numberLabel];
}
return self;
}
And this is how it looks with initWithFrame:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.redView = [self redViewWithFrame:frame];
[self addSubview:self.redView];
//label-related stuff
}
return self;
}
- (UIView *)redViewWithFrame:(CGRect)frame {
UIView *view = [[UIView alloc] initWithFrame:frame];
view.backgroundColor = [UIColor redColor];
view.alpha = 1;
return view;
}
And the for-loop, calling these initializers from another class (UIScrollView subclass). The label value is being set after the view had been initialized.
- (void)setNumberOfBlocks:(NSInteger)numberOfBlocks {
_blocks = [[NSMutableArray alloc] init];
CGSize contentSize;
contentSize.width = BLOCK_WIDTH * (numberOfBlocks);
contentSize.height = BLOCK_HEIGHT;
self.contentSize = contentSize;
for (int i = 0; i < numberOfBlocks; i++) {
CGFloat totalWidth = BLOCK_WIDTH * i;
CGRect frame = CGRectMake(0, 0, BLOCK_WIDTH, BLOCK_HEIGHT);
frame.origin.x = totalWidth;
BlockView *view = [[BlockView alloc] initWithImage:[UIImage imageNamed:#"block.png"]];
OR!!!
BlockView *view = [[BlockView alloc] initWithFrame:frame];
view.frame = frame;
NSString *number = [NSString stringWithFormat:#"%ld", (long)i + 1];
view.numberLabel.text = number;
[self addSubview:view];
[_blocks addObject:view];
}
}
Googling gave me the impression that this is very common problem, but I haven't found any solution how to beat this. Moreover, I still do not understand, why numbers are in totally right order, the only problem is view position.
The problem is that you're setting the frame of the red view to the superview's frame instead of its bounds. Since the red view is a subview of the BlockView, its frame needs to be relative to its superview, which you get with bounds (its not clear why you even need the red view, as opposed to setting the background color of the block view to red).
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.redView = [self redViewWithFrame:self.bounds];
[self addSubview:self.redView];
//label-related stuff
}
return self;
}
I think you should set the frame origin to (0,0) in redViewWithFrame in ordre to hâve superposed views
I am having huge problems with learning autolayout especially when integrating xibs and uiscrollviews. In an effort to simplify my problem, I started a new project with a single view tied to a storyboard. I then subclassed UIView (Diptic) and created a xib file for it. My storyboard is not using autolayout, but my Diptic xib is. Right now I want to have a horizontal scrollView with a few Diptic instances layed out across it. But I am only ever getting the first diptic instance to show up, because the frame isn't being initialized correctly.
In my ViewController.m's viewDidLoad:
self.scrollView.contentSize = CGSizeMake((self.view.frame.size.width+10)*5, self.view.frame.size.height);
for (int i = 0; i < 5; i++){
int x = i*(self.view.frame.size.width+10);
Diptic *diptic = [[Diptic alloc] initWithFrame:CGRectMake(x, 50, self.view.frame.size.width, self.view.frame.size.height-100)];
[self.scrollView addSubview:diptic];
[array addObject:diptic];
UIView *greenBox = [[UIView alloc] initWithFrame:CGRectMake(x, 5, 40, 40)];
greenBox.backgroundColor = [UIColor greenColor];
[self.scrollView addSubview:greenBox];
}
Diptic.m
#import "Diptic.h"
#implementation Diptic
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray* views = [[NSBundle mainBundle] loadNibNamed:#"Diptic" owner:nil options:nil];
self = [views objectAtIndex:0];
self.label.text = #"WOOT";
self.backgroundColor = [UIColor redColor];
}
return self;
}
#end
If I set the frame after I add it to the view it seems to work, but why can't I set the frame with initWithFrame?
The problem here is that you assign the frame to a view that is created with a call to [super initWithFrame:frame]. When the NIB is loaded in - (id)initWithFrame:(CGRect)frame, self is replaced with a view from [views objectAtIndex:0] and the frame for this view is never set. Instead, eliminate the call to super and load the view from the NIB instead:
#import "Diptic.h"
#implementation Diptic
- (id)initWithFrame:(CGRect)frame
{
NSArray *views = [[NSBundle mainBundle] loadNibNamed:#"Diptic" owner:nil options:nil];
self = [views objectAtIndex:0];
if (self) {
self.frame = frame;
self.label.text = #"WOOT";
self.backgroundColor = [UIColor redColor];
}
return self;
}
#end
When init a view/controller from storyboard or from xib, the init method is
- (id)initWithCoder:(NSCoder *)decoder
try to do other things in this method
I have a UITableView with custom UITableViewCells. The content of the cell is kept in a separate class extending UIView (i have 3 kind of contents which i switch by hiding and showing views, i took this approach because of the way i wanted to make the transition between cells).
So let's assume i have one of the views visible and added to the contentView of the cell. This view contains some text and some rectangles made of UIViews. Everything good till now, but the weird thing is when i touch the cell, the rectangles simply disappears, the text stays the same. Do you know what might be the problem? I tried to add the view to the backgroundView as well, it's doing the same.
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.active = NO;
state = -1;
// Touch is not working if the view has no bounds
self.backgroundView = [[UIView alloc] init];
self.backgroundColor = [UIColor clearColor];
self.selectedBackgroundView = [[UIView alloc] init];
self.selectedBackgroundView.backgroundColor = [UIColor clearColor];
self.clipsToBounds = YES;
self.contentView.clipsToBounds = YES;
// Add empty view
emptyView = [[View1 alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) andRadius:CELL_DOT_RADIUS];
emptyView.userInteractionEnabled = NO;
[self.backgroundView addSubview:emptyView];
The view:
- (id) initWithFrame:(CGRect)frame andRadius:(int)r {
self = [super initWithFrame:frame]; radius = r;
if (self) {
int outerlineWeight = 1;
timelineView = [[UIView alloc] initWithFrame:CGRectMake(frame.size.width/4, frame.size.height/2, 1, 1)];
[self addSubview:timelineView];
dotView = [[UIView alloc] initWithFrame:CGRectMake(frame.size.width/4-radius, frame.size.height/2-radius, radius*2, radius*2)];
dotView.layer.cornerRadius = radius;
dotView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:dotView];
UIView *n = [[UIView alloc] initWithFrame:CGRectMake(160, 0, 50, 20)];
n.backgroundColor = [UIColor redColor];
[self addSubview:n];
middleText = [[UILabel alloc] initWithFrame:dotView.frame];
middleText.font = [UIFont systemFontOfSize:12];
middleText.textColor = [UIColor grayColor];
middleText.backgroundColor = [UIColor clearColor];
middleText.textAlignment = NSTextAlignmentCenter;
[self addSubview:middleText];
This are the sources so you can try for yourself if you want. As you can see the orange rectangle disappears but the text not. For what i need to do nothing should disappear, in the best case i want to change their colours. http://ge.tt/6wRBObD1/v/0?c
You are adding it to background view. When selected the selected background view will display not background view. In your custom cell try
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
if (selected) {
[self.backgroundView addSubview:emptyView];
}
else{
[self.selectedBackgroundView addSubview:emptyView];
}
// Configure the view for the selected state
}
Or add empty view to contentview
one thing for frame settings u need to override "layoutsubviews" method ...
in custom cell
init all the views in initialisation method i,e ur - (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier method and add it to cell
in - (void)layoutSubviews just set the frame for ur views in the cell,
use tag property to access the views in the layoutsubviews, if it is not the property
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.active = NO;
state = -1;
// Touch is not working if the view has no bounds
self.backgroundView = [[UIView alloc] init];
self.backgroundColor = [UIColor clearColor];
self.selectedBackgroundView = [[UIView alloc] init];
self.selectedBackgroundView.backgroundColor = [UIColor clearColor];
self.clipsToBounds = YES;
self.contentView.clipsToBounds = YES;
// Add empty view
//emptyView = [[View1 alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) andRadius:CELL_DOT_RADIUS];//dont set the frame heare do it layoutsubviews
emptyView = [[View1 alloc] init];
emptyView.userInteractionEnabled = NO;
emptyView.tag = 100;
[self.backgroundView addSubview:emptyView];
- (void)layoutSubviews
{
[super layoutSubviews];
UIView *emptyView = [self viewWithTag:100];//your background view heare u can get the frame values for ur cell
emptyView.frame = self.bounds;//better do it for other views in cell also
//test it by setting some background color
}
Hope this helps u ...:)
Ok, so like i've said in my last comment the backgroundColor of any subview is the problem, in the selected state is cleared. For cells created in interface builder the problem does not occurs, my cells are created programatically.
I fixed this by drawing with CoreGraphics in drawRect method.
As with a UICollectionView a UITableView has a background view that is build before AutoLayout. If you use autoLayout you should make sure the backgroundView has a frame. Otherwise is will disappear.
In your cell subclass you can do:
-(void)setBackgroundView:(UIView *)backgroundView
{
super.backgroundView = backgroundView;
self.backgroundView.translatesAutoresizingMaskIntoConstraints = NO;
[self.backgroundView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
}
In swift you need to declare viewcontroller object globally that would result in Strong, in case if you declare locally it results in keep disappearing the cells.
var refineViewController : RefineViewController?
then you can access that controller using below code that would not result in disappearing cells.
func showRefineView(isFindHomeTab isFindHomeTab : Bool){
refineViewController = RefineViewController(nibName: String(BaseGroupedTableVC),bundle : nil)
refineViewController!.refineSearchDelegate = self
refineViewController!.view.frame = CGRectMake(0, -490, self.view.frame.size.width, self.view.frame.size.height)
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseOut, animations:
{
self.refineViewController!.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.refineViewController!.isFindHomeTab = isFindHomeTab
}, completion: nil)
self.view.addSubview(refineViewController!.view)
}
I want to position a view (red box with label and button) prepared in IB as Subview on the screen programmatically. The positioning works fine with the "blue lines" (there might actually be a better way to simply draw a line on a view?!). But the view of the "AttributeApertureView" view object sticks to the top instead of following the initFrame Parameter starting at y=60 as you can see in the screenshot.
//Add blue Line
CGRect lineB = CGRectMake(0, 48, bounds.size.width, 0.5);
UIView *secondLine = [[UIView alloc]initWithFrame:lineB];
[secondLine setBackgroundColor:[UIColor colorWithRed:0.396 green:0.796 blue:0.894 alpha:1]];
[[self view]addSubview:secondLine];
//Add Attribute Aperture
AttributeApertureView *aperture = [[AttributeApertureView alloc]initWithFrame:CGRectMake(0, 60, bounds.size.width, 50)];
[aperture setBackgroundColor:[UIColor redColor]];
[[self view]addSubview:aperture];
Init function in AttributeApertureView class. This should basically only load the related nib file with the IB Interface.
#implementation AttributeApertureView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"AttributeApertureView"
owner:self
options:nil];
self = [nib objectAtIndex:0];
}
return self;
}
What is the best way to position the "aperture" view on the screen?
Seems like calling loadNibNamed: resets the view's frame to what it is in the nib. This should work:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"AttributeApertureView"
owner:self
options:nil];
self = [nib objectAtIndex:0];
self.frame = frame;
}
return self;
}
because self = [super initWithFrame:frame]; sets the frame once, but self = [nib objectAtIndex:0]; ends up changing it again because you are resetting the whole view, so you have to set the frame again to be the one in the argument.