How to send array to subview and then print into label? - objective-c

Working over storyboard.
I've created View Controller (storyboard) and then in middle of content added subview from xib file.
I want to add xib (UIView) like as subview into ViewController and send object with data and print that data into label but I don't know how.
Here is my code.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
UIView *subView;
}
#property (strong, nonatomic) IBOutlet UIView *subView; //connected over IB
#end
ViewController.m
#import "OfferViewController.h"
#import "OfferLocation.h"
#interface OfferViewController ()
#end
#implementation OfferViewController
#synthesize subView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
OfferLocation *location = [[OfferLocation alloc] initWithFrame:CGRectZero];
[self.subView addSubview:location];
}
...
#end
and here is subview:
OfferLocation.h
#import <UIKit/UIKit.h>
#interface OfferLocation : UIView{
UIView *view;
UILabel *locationLabel;// here is that label taht I want to print into
}
#property (nonatomic, retain) IBOutlet UIView *view;// connected over IB
#property (nonatomic, retain) IBOutlet UILabel *locationLabel;
#end
OfferLocation.m
#import "OfferLocation.h"
#implementation OfferLocation
#synthesize view, locationLabel;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
locationLabel.text = #"some text"; //this is not working
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:#"OfferLocation" owner:self options:nil];
UIView *tempView = [subviewArray objectAtIndex:0];
[self addSubview:tempView];
}
return self;
}

subView never seems to be initialized and loaded to the view or presented. Therefore you cannot see it.
Try calling:
self.view = self.subView // or subView; // or [self.view addSubview:self.subView // or subview];
or something similiar
Then declare a UILabel and initialize it with whatever text you want and add it to subview:
UILabel *label = [[UILabel alloc] initWithString:#"StackOverflow rocks!"];
[self.subView addSubview:label];
// or [self.view addSubview:label];
Differing on how you set subView.
What is this data you want to set on label's text? If it is a data type use the specifiers in the string.
%i // for int
%# // for string or object adress
%c // for char
%f // for float
etc...

Related

How to set values of subclassed UIView properties when loading subclass from a xib

I have a subclassed UIView called BannerHeaderView, and designed the way I want it layed out in an xib. I have set the xib class to BannerHeaderView. I have a UILabel and a UIImageView which I have connected in IB.
The problem is that when I go to set the values of these subViews after initialising my BannerHeaderView in a ViewController, the label and image view are null. I have tried setting them in init also.
Code for BannerHeaderView.h:
#interface BannerHeaderView : UIView
#property (strong, nonatomic) IBOutlet UIImageView *bannerImage;
#property (strong, nonatomic) IBOutlet UILabel *headerLabel;
-(void)setTitle:(NSString *)title;
-(void)setImageFile:(PFFile *)imageFile;
#end
Code for BannerHeaderView.m:
#implementation BannerHeaderView
#synthesize headerLabel, bannerImage;
-(id)init{
self = [super init];
if (self) {
[self customInit];
}
return self;
}
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self customInit];
}
return self;
}
-(void)customInit{
UIView *contentView = [[[NSBundle mainBundle] loadNibNamed:#"BannerHeaderView"
owner:self
options:nil] objectAtIndex:0];
[self addSubview:contentView];
contentView.frame = self.bounds;
}
-(void)setTitle:(NSString *)title{
NSLog(#"HEADER = %#", headerLabel);
headerLabel.text = title;
}
And I am creating the BannerHeaderImage in my ViewController like so:
bannerHeader = [[BannerHeaderView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, bannerHeight + segmentedHeaderHeight)];
[bannerHeader setTitle:#"I AM THE NEW TITLE"];
The log tells me that the headerLabel is null.
Questions:
How do I set the values of these subviews?
Should I just design the layout of this programatically?
Thanks for your time.
P.S. I have spent hours researching this and I can't find a solution. I did find similar questions on SO but none with suitable answers to enable me to solve my problem...
Please set the class BannerHeaderView to File's Owner like this

add custom UIView and xib into storyboard

I have a custom UIView and xib called DialPad and I'm trying to use this object in my storyboard, but the custom DialPad isn't being add as a subview with the buttons
my custom DialPad :UIView
#implementation DialPad
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor clearColor];
}
return self;
}
my custom xib called DialPad
and my view controllers look like this
#import <UIKit/UIKit.h>
#import "DialPad.h"
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIView *dial;
#end
#import "ViewController.h"
#interface ViewController ()
{
DialPad *d;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
d = [[DialPad alloc] initWithFrame:self.dial.frame];
[self.dial addSubview:d];
}
#end
and my storyboard
but the border around the view looks strange
#import "DialPad.h"
#import <QuartzCore/QuartzCore.h>
#implementation DialPad
- (void)drawRect:(CGRect)rect
{
// Drawing code
self.layer.borderColor = [UIColor redColor].CGColor;
self.layer.borderWidth = 1;
}
#end
For loading a view from xib file, you should do this:
d = [[[NSBundle mainBundle] loadNibNamed:#"DialPad" owner:nil options:nil]
firstObject];
[self.dial addSubview:d];
Border: try to add border code in - (void)awakeFromNib

Xcode: How do I change UIPageControl value with swipe gesture?

I have a quick question I was hoping you guys could help me answer. Right now I have a UIPageControl in a storyboard which changes an image depending on what dot you are on, however, as of now you have to press on the dot to change through the dots/images, how can I change through the images/dots by swiping?
Here is my code for my .h
#import <UIKit/UIKit.h>
#interface PageViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIImageView *dssview;
- (IBAction)changephoto:(UIPageControl *)sender;
#end
Here is my code for my .m
#import "PageViewController.h"
#interface PageViewController ()
#end
#implementation PageViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)changephoto:(UIPageControl *)sender {
_dssview.image = [UIImage imageNamed:
[NSString stringWithFormat:#"%d.jpg",sender.currentPage+1]];
}
#end
Any help would be greatly appreciated.
Thanks
You can add UISwipeGestureRecognizer to your view and in the selector method of UISwipeGestureRecognizer based on the direction update the UIPageControl object, either increment the current page or decrement.
You can refer the below code.
Adding swipe gesture to the view controller
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipe:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeLeft];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipe:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRight];
Swipe gesture selector
- (void)swipe:(UISwipeGestureRecognizer *)swipeRecogniser
{
if ([swipeRecogniser direction] == UISwipeGestureRecognizerDirectionLeft)
{
self.pageControl.currentPage -=1;
}
else if ([swipeRecogniser direction] == UISwipeGestureRecognizerDirectionRight)
{
self.pageControl.currentPage +=1;
}
_dssview.image = [UIImage imageNamed:
[NSString stringWithFormat:#"%d.jpg",self.pageControl.currentPage]];
}
Add an outlet to the UIPageControl in the .h file
#interface PageViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIImageView *dssview;
#property (strong, nonatomic) IBOutlet UIPageControl *pageControl;
- (IBAction)changephoto:(UIPageControl *)sender;
#end

How to save UIImages in view

In my app I have two views: a mapView, and a detail view. The mapView has annotations, and the annotation views have right callout buttons that push the detail view onto the stack when the callout button is pressed. In the detail view, the user can take a picture that appears on the UIImage that is on the detail view controller. What I want is for a different image to be on the detail view controller for each annotation. I have read that I can use a singleton, and I have made a singleton class, but I do not know how to use it. Can someone help me out?
Here is some code:
My MKAnnotation class:
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface MapPoint : NSObject <MKAnnotation>
{
NSString *_address;
CLLocationCoordinate2D _coordinate;
NSNumber *_identifier;
UIImage *_image;
}
- (id)initWithAddress:(NSString*)address
coordinate:(CLLocationCoordinate2D)coordinate
title:(NSString *)t
identifier:(NSNumber *)ident;
//This is a required property from MKAnnotation
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
//This is an optional property from MKAnnotataion
#property (nonatomic, copy) NSString *title;
#property (nonatomic, readonly, copy) NSString *subtitle;
#property (nonatomic) BOOL animatesDrop;
#property (nonatomic) BOOL canShowCallout;
#property (copy) NSString *address;
#property (copy) NSNumber *identifier;
#property (copy,nonatomic) UIImage *image;
#end
#implementation MapPoint
#synthesize title, subtitle, animatesDrop, canShowCallout;
#synthesize address = _address, coordinate = _coordinate, identifier = _identifier, image = _image;
-(id)initWithAddress:(NSString *)address
coordinate:(CLLocationCoordinate2D)coordinate
title:(NSString *)t
identifier:(NSNumber *)ident
{
self = [super init];
if (self) {
_address = [address copy];
_coordinate = coordinate;
_identifier = ident;
[self setTitle:t];
NSDate *theDate = [NSDate date];
subtitle = [NSDateFormatter localizedStringFromDate:theDate
dateStyle:NSDateFormatterMediumStyle
timeStyle:NSDateFormatterMediumStyle];
}
return self;
}
#end
Here is the detail view controller:
#import <UIKit/UIKit.h>
#class P2OViewController;
#interface PinViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextFieldDelegate>
{
__weak IBOutlet UILabel *label;
__weak IBOutlet UIButton *removeButton;
NSString *addressForLabel;
__weak P2OViewController *_vc;
__weak NSNumber *_identifier;
}
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet UIButton *removeButton;
#property (weak, nonatomic) P2OViewController *vc;
#property (weak, nonatomic) NSNumber *identifier;
-(void)takePicture:(id)sender;
-(void)buttonPressed:(id)sender;
#end
#import "PinViewController.h"
#import "MapPoint.h"
#import "P2OViewController.h"
#implementation PinViewController
#synthesize imageView, label, removeButton;
#synthesize vc = _vc, identifier = _identifier;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UIBarButtonItem *pic = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera
target:self
action:#selector(takePicture:)];
[[self navigationItem]setRightBarButtonItem:pic];
}
return self;
}
-(void)takePicture:(id)sender
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
//If our device has a camera, we ant to take a picture, otherwise, we just pick from photo library
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
} else {
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
[imagePicker setDelegate:self];
//Place the image picker on the screen
[self presentViewController:imagePicker
animated:YES
completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//Get picked image from info dictionary
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//Put the image onto the screen in out image view
[imageView setImage:image];
//Take image picker off the screen - you must call this dismiss method
[self dismissViewControllerAnimated:YES
completion:nil];
}
#end
You surely have a class implementing the MKAnnotation protocol.
In this class simply add a UIImage property and assign to every annotation its custom image.
Then when presenting the detailed view you just pass around the annotation and access its image property you defined.
EDIT
In your PinViewController simply declare a property like this
#property(nonatomic, strong) MapPoint * annotation;
Before you present your PinViewController assign the corresponding annotation to it, doing something like
detailedController.annotation = theAnnotation;
Do whatever you need to do to get the image, then store it in the annotation in this way
self.annotation.image = theImage;
Now the annotation is storing the image, so as long as you keep it in memory it will be there available for you.
The next time you push the detailed view you can perform a check to see whether that annotation has already an image or not
if(nil != self.annotation.image) {
// do something
} else {
// do something else
}

if statement not working

I have an app where there is a timer. It goes from 10 to 0. Using NSTimer. I have said:
.m:
//
// Skin.m
// PopThatPimple
//
// Created by Rohan Kapur on 6/2/11.
// Copyright 2011 UWCSEA. All rights reserved.
//
#import "Skin.h"
#implementation Skin
#synthesize theAudio;
#synthesize label;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *myTouch = [touches anyObject];
CGPoint point = [myTouch locationInView:pimple];
if ( CGRectContainsPoint(pimple.bounds, point) ) {
[self checkcollision];
}
}
-(void)checkcollision {
pimple.center = CGPointMake(
random() % (unsigned int)theview.bounds.size.width,
random() % (unsigned int)theview.bounds.size.height
);
score.text = [NSString stringWithFormat:#"%d", ([score.text intValue] + 1)];
sad.hidden = NO;
NSURL* popURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"pop" ofType:#"mp3"]];
AudioServicesCreateSystemSoundID((CFURLRef) popURL, &popID);
AudioServicesPlaySystemSound(popID);
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
-(void)showActivity{
int currentTime = [time.text intValue];
int newTime = currentTime + -1;
time.text = [NSString stringWithFormat:#"%d", newTime];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)viewDidLoad {
myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector (showActivity) userInfo:nil repeats:YES];
[label2 setHidden:YES];
[super viewDidLoad];
}
-(void)void2 {
if ([label3.text isEqualToString:#"0"]) {
[[self view] addSubview:timeup];
score.text = label2.text;
label2.hidden = NO;
}
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
-(void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
-(void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
.h:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface Skin : UIViewController {
IBOutlet UIImageView *pimple;
IBOutlet UIImageView *smile;
IBOutlet UIImageView *sad;
AVAudioPlayer *theAudio;
IBOutlet UIView *theview;
SystemSoundID popID;
IBOutlet UIImageView *face;
IBOutlet UIImageView *face2;
IBOutlet UIImageView *face3;
IBOutlet UIImageView *face4;
IBOutlet UIImageView *face5;
IBOutlet UIImageView *face6;
IBOutlet UIImageView *face7;
IBOutlet UIImageView *face8;
IBOutlet UIImageView *face9;
IBOutlet UIImageView *face10;
IBOutlet UIImageView *face11;
IBOutlet UIImageView *face12;
IBOutlet UIImageView *face13;
IBOutlet UIImageView *face14;
IBOutlet UIImageView *face15;
IBOutlet UILabel *label2;
IBOutlet UILabel *score;
IBOutlet UIImageView *skin;
IBOutlet UILabel *time;
NSTimer * myTicker;
IBOutlet UILabel *label3;
IBOutlet UIImageView * timeup;
}
-(IBAction)start;
-(void)void2;
-(void)showActivity;
#property (nonatomic, retain) UILabel *label;
#property (nonatomic, retain)AVAudioPlayer *theAudio;
-(void)checkcollision;
#end
I have not used all of my outlets and ibactions yet. And i have not used avfoundation yet
I have CONNECTED EVERYTHING! I HAVE CHECKEED A THOUSAND TIMES! When it reaches zero nothing happens and the timer just goes to the negatives. WHat am I doing wrong?
There are two major problems here, the first is you're using an assignment operator, not a comparison operator, I'd imagine you have a warning on that.
The second is an == comparison is useless here, the fixed code would be.
if ([label3.text isEqualToString:#"0"])
I'll second (third?) what #BoltClock and #Joshua Weinberg wrote, but add that checking the text displayed in a label is a poor way to determine whether a timer has expired. At some point, somewhere in your program, you're setting the label's text to #"0", so you already know that that condition is true. Likewise with the score... your controller should know what the score is, and it definitely shouldn't be relying on a label to get it.
Don't store data in your view objects. Data should flow from your model through your controller to your view. It only flows in the opposite direction when you're accepting user input.