I'm trying to implement an questionnaire app.
I have an UIPageViewController attached to the main view controller called QuizPageViewController.m. other controllers such as buttons are placed in content view controller called QuizContentViewController.m.
Now my question is how do I navigate pages of UIPageViewController programmatically from QuizContentViewController.m (eg. when buttonDoneClicked clicked)? I'm already aware of the fact that i can programmatically navigate pages using following command but my problem is I don't have access to its arguments from content view controller (QuizContentViewController).
setViewControllers:direction:animated:completion:.
following is my code.
QuizPageViewController.h
#import <UIKit/UIKit.h>
#import "QuizContentViewController.h"
#class QuizPageViewController;
#protocol QuizPageViewControllerDelegate <NSObject>
#optional // Delegate protocols
- (void)dismissReaderViewController:(QuizPageViewController *)viewController;
#end
#interface QuizPageViewController : UIViewController <UIPageViewControllerDataSource, QuizContentViewControllerDelegate>{
}
- (void)moveForward:(id)sender;
- (void)moveBackwards:(id)sender;
- (void)abort:(id)sender;
#property (nonatomic, unsafe_unretained, readwrite) id <QuizPageViewControllerDelegate> delegate;
#property (nonatomic, strong) UIPageViewController *pageView;
#end
QuizPageViewController.m
#import "QuizPageViewController.h"
#interface QuizPageViewController ()
#end
#implementation QuizPageViewController
#synthesize pageView, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[self QuestionDet];
[super viewDidLoad];
// Do any additional setup after loading the view.
NSDictionary *option = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin] forKey:UIPageViewControllerOptionSpineLocationKey];
pageView = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:option];
[pageView setDataSource:self];
QuizContentViewController *initialVC = [self viewControllerAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:initialVC];
[pageView setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
CGRect viewRect = self.view.bounds;
[[pageView view] setFrame:viewRect];
[self addChildViewController:self.pageView];
[self.view addSubview:[pageView view]];
[pageView didMoveToParentViewController:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger) indexOfViewController:(QuizContentViewController *)viewController{
return viewController.dataObjquizNo;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
int index = [self indexOfViewController:(QuizContentViewController *)viewController];
if (index == 0 || index == NSNotFound) {
return nil;
}
index --;
return [self viewControllerAtIndex:index];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
int index = [self indexOfViewController:(QuizContentViewController *)viewController];
if (index == NSNotFound) {
return nil;
}
index++;
return [self viewControllerAtIndex:index];
}
- (QuizContentViewController *)viewControllerAtIndex:(NSInteger)index{
if (index > [quizdet count] - 1) {
return nil;
}
QuizContentViewController *cVC = [[QuizContentViewController alloc] init];
cVc.delegate = self;
Questions *quizz = [quizdet objectAtIndex:index];
[cVC setDataObjQuiz:[quizz quiz]];
[cVC setDataObjAns1:[quizz answer1]];
[cVC setDataObjAns2:[quizz answer2]];
[cVC setDataObjAns3:[quizz answer3]];
[cVC setDataObjAns4:[quizz answer4]];
[cVC setDataObjquizNo:index];
[cVC setDataObjtotalNoOfQuiz:[quizdet count]];
return cVC;
}
- (void)moveForward:(id)sender{
// Navigation forward code should goes here...
}
- (void)moveBackwards:(id)sender{
// Navigation backwards code should goes here...
}
- (void)abort:(id)sender{
[delegate dismissReaderViewController:self];
}
}
QuizContentViewController.h
#import <UIKit/UIKit.h>
#class QuizContentViewController;
#protocol QuizContentViewControllerDelegate <NSObject>
- (void)moveForward:(id)sender;
- (void)moveBackwards:(id)sender;
- (void)abort:(id)sender;
#end
#interface QuizContentViewController : UIViewController{
UITextView *txtVwQuiz;
UILabel *lblSummery;
NSString *dataObjQuiz;
NSString *dataObjAns1;
NSString *dataObjAns2;
NSString *dataObjAns3;
NSString *dataObjAns4;
NSInteger dataObjquizNo;
NSInteger dataObjtotalNoOfQuiz;
}
#property(nonatomic, unsafe_unretained, readwrite) id <QuizContentViewControllerDelegate> delegate;
#property (nonatomic, strong) NSString *dataObjQuiz;
#property (nonatomic, strong) NSString *dataObjAns1;
#property (nonatomic, strong) NSString *dataObjAns2;
#property (nonatomic, strong) NSString *dataObjAns3;
#property (nonatomic, strong) NSString *dataObjAns4;
#property NSInteger dataObjquizNo;
#property NSInteger dataObjtotalNoOfQuiz;
#end
QuizContentViewController.m
#import "QuizContentViewController.h
#import <QuartzCore/QuartzCore.h>
#define isPhone568 ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height == 568)
#define iPhone568ImageNamed(image) (isPhone568 ? [NSString stringWithFormat:#"%#-568h.%#", [image stringByDeletingPathExtension], [image pathExtension]] : image)
#define iPhone568Image(image) ([UIImage imageNamed:iPhone568ImageNamed(image)])
# define IS_IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone
#interface QuizContentViewController ()
#end
#implementation QuizContentViewController
#synthesize dataObjQuiz, dataObjAns1, dataObjAns2, dataObjAns3, dataObjAns4, dataObjquizNo, dataObjtotalNoOfQuiz, delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor clearColor]; // Transparent
UIImageView *backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:iPhone568ImageNamed(#"QuizPage.png")]];
[self.view addSubview:backgroundImage];
[self.view sendSubviewToBack:backgroundImage];
// Do any additional setup after loading the view.
// Override point for customization after application launch
CGSize viewSize = self.view.bounds.size;
float boader;
float heightofSubVw;
boader = IS_IPAD?15:37;
heightofSubVw = viewSize.height/10;
lblSummery = [[UILabel alloc] initWithFrame:CGRectMake(boader, 5, viewSize.width-(2*boader), heightofSubVw*1)];
[lblSummery setBackgroundColor:[UIColor clearColor]];
[lblSummery setTextAlignment:UITextAlignmentLeft];
[lblSummery setFont:[UIFont systemFontOfSize:IS_IPAD?14.f:28.f]];
[lblSummery setText:[NSString stringWithFormat:#" Question %d out of %d.",dataObjquizNo+1, dataObjtotalNoOfQuiz]];
[lblSummery setTextColor:[UIColor orangeColor]];
[self.view addSubview:lblSummery];
txtVwQuiz = [[UITextView alloc] initWithFrame:CGRectMake(boader, heightofSubVw, viewSize.width-(2*boader), heightofSubVw*4)];
[txtVwQuiz setText:dataObjQuiz];
[txtVwQuiz setBackgroundColor:[UIColor clearColor]];
[txtVwQuiz setTextAlignment:UITextAlignmentLeft];
[txtVwQuiz setTextColor:[UIColor whiteColor]];
[txtVwQuiz setFont:[UIFont systemFontOfSize:IS_IPAD?15.f:30.f]];
[txtVwQuiz setEditable:NO];
[self.view addSubview:txtVwQuiz];
NSArray *options =[[NSArray alloc]
initWithObjects:dataObjAns1,dataObjAns2,dataObjAns3,dataObjAns4,nil];
MIRadioButtonGroup *group =[[MIRadioButtonGroup alloc]
initWithFrame:CGRectMake(boader, heightofSubVw*4, viewSize.width-(2*boader), heightofSubVw*5)
andOptions:options andColumns:1];
[self.view addSubview:group];
UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(boader+(IS_IPAD?6:12), heightofSubVw*8.5, IS_IPAD?44:88, IS_IPAD?44:88)];
[btnBack addTarget:self action:
#selector(navButtonBackClicked:)
forControlEvents:UIControlEventTouchUpInside];
btnBack.contentHorizontalAlignment =
UIControlContentHorizontalAlignmentCenter;
[btnBack setBackgroundImage:[UIImage imageNamed:
#"Navigation_Back.png"] forState:UIControlStateNormal];
[self.view addSubview:btnBack];
UIButton *btnDone = [[UIButton alloc] initWithFrame:CGRectMake(viewSize.width - (boader+(IS_IPAD?10 + 44 :20 + 88)), heightofSubVw*8.5, IS_IPAD?44:88, IS_IPAD?44:88)];
[btnDone addTarget:self action:
#selector(navButtonDoneClicked:)
forControlEvents:UIControlEventTouchUpInside];
btnDone.contentHorizontalAlignment =
UIControlContentHorizontalAlignmentCenter;
[btnDone setBackgroundImage:[UIImage imageNamed:
#"Navigation_Done.png"] forState:UIControlStateNormal];
[self.view addSubview:btnDone];
UIButton *btnAbort = [[UIButton alloc] initWithFrame:CGRectMake(viewSize.width - (boader+(IS_IPAD?2*10 + 88:2*20 + 176)), heightofSubVw*8.5, IS_IPAD?44:88, IS_IPAD?44:88)];
[btnAbort addTarget:self action:
#selector(navButtonAbortClicked:)
forControlEvents:UIControlEventTouchUpInside];
btnAbort.contentHorizontalAlignment =
UIControlContentHorizontalAlignmentCenter;
[btnAbort setBackgroundImage:[UIImage imageNamed:
#"Navigation_Abort.png"] forState:UIControlStateNormal];
[self.view addSubview:btnAbort];
}
-(IBAction) navButtonDoneClicked:(UIButton *) sender{
id index;
index = [NSNumber numberWithInt:dataObjquizNo];
if ([delegate respondsToSelector:#selector(moveForward:)]) {
[delegate moveForward:index];
}
}
-(IBAction) navButtonAbortClicked:(UIButton *) sender{
id index;
index = [NSNumber numberWithInt:dataObjquizNo];
if ([self.delegate respondsToSelector:#selector(abort:)]) {
[self.delegate abort:index];
}
}
-(IBAction) navButtonBackClicked:(UIButton *) sender{
id index;
index = [NSNumber numberWithInt:dataObjquizNo];
if ([delegate respondsToSelector:#selector(moveBackwards:)]) {
[delegate moveBackwards:index];
}
}
If I understand your question correctly, the QuizContentViewController's view has buttons that are pressed and once pressed it needs to notify your mainviewcontroller so it can set the view appropriately on QuizPageViewController? If this is the case, protocols are a great way for viewcontrollers to send messages to other viewcontrollers. Here is apple documentation about protocols: Working with Protocols.
Protocols are a little tricky the first time you use them. Once everything is set-up correctly you should be able to do something like this:
-(void)buttonBackClicked:(id)sender
{
[self.delegate shouldMoveBack];
}
Related
I am trying to use pure code to create UI practice block pass value between viewController. But the callback block didn't work. The NSLog method didn't print anything on debug area. Here's the code. Give me some tips, thank you.
VC.h
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
#property (copy, nonatomic) void (^callBack)(NSString *text);
#end
VC.m
- (UITextField *)textField {
if (!_textField) {
_textField = [[UITextField alloc] init];
_textField.backgroundColor = [UIColor whiteColor];
}
return _textField;
}
- (UIButton *)button {
if (!_button) {
_button = [[UIButton alloc] init];
_button.backgroundColor = [UIColor blueColor];
[_button addTarget:self action:#selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
}
return _button;
}
- (void)setupUI {
[self.view addSubview:self.textField];
[self.view addSubview:self.button];
[self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(200);
make.height.mas_equalTo(50);
make.centerX.mas_equalTo(self.view.mas_centerX);
make.centerY.mas_equalTo(self.view);
}];
[self.button mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(200);
make.height.mas_equalTo(50);
make.centerX.mas_equalTo(self.view);
make.centerY.mas_equalTo(self.view).offset(100);
}];
}
- (void)buttonAction {
NSString *str = self.textField.text;
if (self.callBack != nil) {
self.callBack(str);
NSLog(#"This statement didnt print in log");
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor redColor];
}
update code
VC2.m
- (void)viewWillAppear:(BOOL)animated{
self.callBack = ^(NSString *text){
};
}
- (void)buttonAction {
if (self.callBack) {
NSLog(#"It worked on debug area %#", self.textField.text);
self.callBack(self.textField.text);
}
self.textField.text = #"";
}
VC1.m
- (void)viewDidLoad {
[super viewDidLoad];
_secondVc = [[SecondViewController alloc] init];
_secondVc.callBack = ^(NSString *str){
};
[self setupUI];
self.view.backgroundColor = [UIColor greenColor];
}
- (void)viewWillAppear:(BOOL)animated {
if (_secondVc.callBack != nil) {
NSLog(#"It wrked on debug screen");
_secondVc.callBack = ^(NSString *str){
NSLog(#"It didn't worked on debug screen");
//I want set my label.text = str;
};
};
}
The only way is that you property
#property (copy, nonatomic) void (^callBack)(NSString *text);
is empty. Try to put breakpoint in buttonAction method and look at the property.
As Sander and KrishnaCA mentioned your callBack is nil. I would suggest you create a definition of the block like this:
typedef void(^TextBlock)(NSString *text);
Then change your property to:
#property (copy, nonatomic) TextBlock callBack;
Create a copy of the block in your first view controller:
#interface FirstViewController()
#property (copy, nonatomic) TextBlock firstViewControllerCallBack;
#end
Initialize the callback copy (i.e. in viewDidLoad)
- (void)viewDidLoad {
[super viewDidLoad];
self.firstViewControllerCallBack = ^(NSString *text){
NSLog(#"Second view controller's button tapped!");
};
}
Assign the callback to the second view controller right before presenting/pushing it:
SecondViewController *secondVC = [[SecondViewController alloc] init];
secondVC.callBack = self.firstViewControllerCallBack; // Assign the callback
// ... Presenting the view controller
Clean up the completion block after you done with it (i.e. in viewWillDisappear):
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.firstViewControllerCallBack = nil;
}
I am a new programmer, and know the basics of IOS and Objective C Programming, but have run into a bug.
All I am trying to do is when a button is clicked, it calls a method from another class.
The Method I am trying to call is: [phoneCompany printPrompt];
So here is my code:
First Class: (ViewController)
.m
#import "ViewController.h"
#import "PhoneCompany.h"
#implementation ViewController
#synthesize dialTextField;
#synthesize dialButton;
#synthesize textFromCall;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.dialTextField = [[UITextField alloc]initWithFrame:CGRectMake(83, 101, 154, 30)];
self.dialTextField.borderStyle = UITextBorderStyleRoundedRect;
self.dialTextField.placeholder = #"Dial Number";
self.dialTextField.textAlignment = NSTextAlignmentCenter;
self.dialTextField.adjustsFontSizeToFitWidth = YES;
self.dialTextField.minimumFontSize = 20;
self.dialTextField.autocorrectionType = NO;
self.dialTextField.returnKeyType = UIReturnKeyDone;
self.dialTextField.backgroundColor = [UIColor lightGrayColor];
self.dialTextField.delegate = self;
[self.view addSubview:self.dialTextField];
self.dialButton= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.dialButton setTitle:#"Dial!" forState:UIControlStateNormal];
self.dialButton.titleLabel.font = [UIFont systemFontOfSize:20];
[self.dialButton setBackgroundColor:[UIColor blueColor]];
[self.dialButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.dialButton addTarget:self action:#selector(mainCall) forControlEvents:UIControlEventTouchUpInside];
self.dialButton.frame =CGRectMake(92, 400, 125, 30);
[self.view addSubview:self.dialButton];
self.textFromCall = [[UILabel alloc]initWithFrame:CGRectMake(48,155,220,240)];
[self.textFromCall setText:#"Hello, what number would you like to call?"];
self.textFromCall.numberOfLines = 0;
self.textFromCall.lineBreakMode = UILineBreakModeWordWrap;
self.textFromCall.adjustsFontSizeToFitWidth = YES;
[self.textFromCall setTextAlignment:NSTextAlignmentCenter];
[self.textFromCall setTextColor:[UIColor blackColor]];
[self.textFromCall setBackgroundColor:[UIColor clearColor]];
[self.view addSubview: self.textFromCall];
}
-(void) mainCall{
if([self.dialTextField.text isEqualToString:#"1234567"]){
self.dialButton.enabled = NO;
self.dialTextField.enabled = NO;
PhoneCompany *phoneCompany = [[PhoneCompany alloc]init];
[NSTimer scheduledTimerWithTimeInterval: 3 target:phoneCompany selector:#selector(printPrompt)
userInfo:nil repeats:NO];
self.textFromCall.text = #"Dialing...";
[NSTimer scheduledTimerWithTimeInterval: 1 target:self selector:#selector(connectingStatement)
userInfo:nil repeats:NO];
}
else if([self.dialTextField.text isEqualToString: nil]){
self.textFromCall.text = #"Please enter a phone number.";
}
else{
self.textFromCall.text = #"Invalid Phone number.";
}
}
-(void)connectingStatement{
self.textFromCall.text = #"Connecting...";
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic) UITextField *dialTextField;
#property (weak,nonatomic) UIButton *dialButton;
#property (strong,nonatomic) UILabel *textFromCall;
-(void) mainCall;
-(void) connectingStatement;
-(void) setString:(NSString *)string;
#end
Now here is the Second Class: (PhoneCompany)
.h
#import <Foundation/Foundation.h>
#interface PhoneCompany : NSObject
-(void) printPrompt;
#end
.m
#import "PhoneCompany.h"
#import "ViewController.h"
#implementation PhoneCompany
-(void) printPrompt{
ViewController *mainView = [[ViewController alloc]init];
mainView.dialTextField.text = #"Test";
}
#end
Your call to printPrompt is fine. The problem is that you are creating a new ViewContoller in the function. The one you created in printPrompt is not the same one where you call that function. I means setString: won't replace the text of textFromCall textfield. Somehow you need to pass ViewController to PhoneCompany as a delegate and call the setString: from it.
Edited:
Try this -
In PhoneCompany.h
#class PhoneCompany;
#protocol PhoneCompanyDelegate <NSObject>
-(void)phoneCompany:(PhoneCompany *)phoneCompay
setString:(NSString *)string;
#end
#interface PhoneCompany : NSObject
#property (nonatomic, assign)id<PhoneCompanyDelegate>delegate;
- (id)initWithDelegate:(id<PhoneCompanyDelegate>)delegate;
- (void) printPrompt;
#end
In PhoneCompay.m
#implementation PhoneCompany
- (id)initWithDelegate:(id<PhoneCompanyDelegate>)delegate
{
self = [super init];
if (self)
{
self.delegate = delegate;
}
return self;
}
-(void) printPrompt
{
if (self.delegate && [self.delegate respondsToSelector:#selector(phoneCompany:setString:)])
{
[self.delegate phoneCompany:self
setString:#"Test"];
}
}
#end
When you create the PhonCompany Object in prinPrompt
PhoneCompany *phoneCompay = [[PhoneCompany alloc] initWithDelegate:self];
In your ViewController.h
#import "PhoneCompany"
#interface ViewController:UIViewController<PhoneCompanyDelegate>
It turns out, all I had to do was declare the textFromCall as a static UILabel *textFromCall, and then declare a method to edit the text. Thanks for all your answers!
I am trying to call another method with Delegate and protocols in my app. I need to send the variable "myData" to another view but for some reasons it doesn't works. I don't know what I am doing wrong with the implementation of delegates and protocols. The delegate never call the action of the protocol.
Sorry I'm new with this.
BLEViewController.h
#import <UIKit/UIKit.h>
#import "BLE.h"
#protocol EnviarDatos <NSObject>
//Metodo que se manda llamar pero se implementa en otra clase
-(void) actualizaDatos:(NSData*)Data;
#end
#interface BLEViewController : UITableViewController <BLEDelegate>
{
//id <EnviarDatos> delegate;
}
#property (nonatomic,assign)id delegate;
#property (nonatomic, retain) NSData *myData;
+ (BLE*) theBLEObject;
- (void) scanForPeripherals;
- (IBAction)connect:(id)sender;
-(void) activaProtocolo;
#end
BLEViewController.m
//
// BLEViewController.m
// DL_RemoteBLE_02
//
// Created by Dave Lichtenstein on 3/16/14.
// Copyright (c) 2014 Dave Lichtenstein. All rights reserved.
//
#import "BLEViewController.h"
static BLE* ble;
static UILabel *statusLabel;
static NSString* connectionStatus = #"Not connected!";
#interface BLEViewController ()
#end
#implementation BLEViewController
#synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
if(ble==nil)
{
// Create our Bluetooth Low Energy object
//
ble = [[BLE alloc] init];
[ble controlSetup];
ble.delegate = self;
}
// Create a toolbar at the bottom of the screen to show status text, etc.
//
// get screen size
//
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGFloat toolbarHeight = 50.0;
CGFloat labelHeight = 50.0;
if(statusLabel==nil) // only create once
{
// create our status label object
//
statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, screenHeight-toolbarHeight-labelHeight, screenWidth, labelHeight)];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont boldSystemFontOfSize:15];
statusLabel.text = #"Connection Status:";
}
// create a toolbar
//
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,screenHeight-toolbarHeight,screenWidth,toolbarHeight)];
toolbar.tintColor = [UIColor blackColor];
/*UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 150, 20)];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.font = [UIFont boldSystemFontOfSize:15];
label.text = #"Status:";
UIBarButtonItem *labeltext = [[UIBarButtonItem alloc] initWithCustomView:label];
UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithTitle:#"" style:UIBarButtonItemStyleDone target:self action:nil];
NSArray *items = [NSArray arrayWithObjects:statusLabel, nil];
toolbar.items = items;
*/
[self.view addSubview:statusLabel];
[self.view addSubview:toolbar];
// Update our status label
statusLabel.text = connectionStatus;
_myData = [[NSData alloc]init];
delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//-------------------------------------------------------
// methods
/////////////////////////////////////////////////////////
+ (BLE*) theBLEObject
{
return ble;
}
-(void) connectionTimer:(NSTimer *)timer
{
if (ble.peripherals.count > 0)
{
[ble connectPeripheral:[ble.peripherals objectAtIndex:0]];
}
NSLog(#"connectionTimer"); // diag
}
// We call this when the view loads to try to connect to our bluetooth perepheral
//
- (void) scanForPeripherals
{
if (ble.activePeripheral)
if(ble.activePeripheral.state == CBPeripheralStateConnected)
{
statusLabel.text = #"Disconnectng from peripheral...";
[[ble CM] cancelPeripheralConnection:[ble activePeripheral]];
return;
}
if (ble.peripherals)
ble.peripherals = nil;
NSLog(#"scanning...");
statusLabel.text = #"Scanning for peripherals...";
[ble findBLEPeripherals:2];
[NSTimer scheduledTimerWithTimeInterval:(float)2.0 target:self selector:#selector(connectionTimer:) userInfo:nil repeats:NO];
//[indConnecting startAnimating];
}
- (IBAction)connect:(id)sender {
[self scanForPeripherals];
}
///////////////////////////////////////////////////////////
#pragma mark - BLE delegate
///////////////////////////////////////////////////////////
NSTimer *rssiTimer;
// When Connected, this will be called
-(void) bleDidConnect
{
NSLog(#"->Connected");
statusLabel.text = #"Connected!";
connectionStatus = #"Connected!";
// Schedule to read RSSI every 1 sec.
rssiTimer = [NSTimer scheduledTimerWithTimeInterval:(float)1.0 target:self selector:#selector(readRSSITimer:) userInfo:nil repeats:YES];
}
// When RSSI is changed, this will be called
-(void) bleDidUpdateRSSI:(NSNumber *) rssi
{
// Append the rssi value to our status label
//
NSString *temp = [NSString stringWithFormat:#"%# (%#)", connectionStatus, rssi];
statusLabel.text = temp;
}
-(void) readRSSITimer:(NSTimer *)timer
{
[ble readRSSI];
}
// When data is comming, this will be called
-(void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
NSData *d = [NSData dataWithBytes:data length:length];
_myData = [NSData dataWithBytes:data length:length];
NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
NSLog(#"Datos en String %#",s);
//_datosdelegate = self;
//Is anyone listening
if([delegate respondsToSelector:#selector(actualizaDatos:)])
{
//send the delegate function with the amount entered by the user
[delegate actualizaDatos:_myData];
NSLog(#"Entro delegado");
}
}
- (void)bleDidDisconnect
{
NSLog(#"->Disconnected");
connectionStatus = #"Disconnected!";
statusLabel.text = #"Disconnected!";
[rssiTimer invalidate];
}
#end
sevenSegmentsViewController.h
#import <UIKit/UIKit.h>
#import "BLEViewController.h"
#import "BLE.h"
#interface sevenSegmentsViewController : UIViewController<EnviarDatos>{
UIImage *unoON;
UIImage *dosON;
UIImage *tresON;
UIImage *cuatroON;
UIImage *cincoON;
UIImage *seisON;
UIImage *sieteON;
UIImage *unoOFF;
UIImage *dosOFF;
UIImage *tresOFF;
UIImage *cuatroOFF;
UIImage *cincoOFF;
UIImage *seisOFF;
UIImage *sieteOFF;
}
#property (strong, nonatomic) IBOutlet UIImageView *uno;
#property (strong, nonatomic) IBOutlet UIImageView *dos;
#property (strong, nonatomic) IBOutlet UIImageView *tres;
#property (strong, nonatomic) IBOutlet UIImageView *cuatro;
#property (strong, nonatomic) IBOutlet UIImageView *cinco;
#property (strong, nonatomic) IBOutlet UIImageView *seis;
#property (strong, nonatomic) IBOutlet UIImageView *siete;
#end
sevenSegmentsViewController.m
//
// sevenSegmentsViewController.m
// iShield
//
// Created by Victor CarreƱo on 29/03/14.
// Copyright (c) 2014 RedBearLab. All rights reserved.
//
#import "sevenSegmentsViewController.h"
#interface sevenSegmentsViewController ()
#end
#implementation sevenSegmentsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
unoOFF = [UIImage imageNamed:#"7segnh.png"];
dosOFF = [UIImage imageNamed:#"7segnv.png"];
tresOFF = [UIImage imageNamed:#"7segnv.png"];
cuatroOFF =[UIImage imageNamed:#"7segnh.png"];
cincoOFF = [UIImage imageNamed:#"7segnh.png"];
seisOFF = [UIImage imageNamed:#"7segnv.png"];
sieteOFF = [UIImage imageNamed:#"7segnh.png"];
unoON = [UIImage imageNamed:#"7segvh.png"];
dosON = [UIImage imageNamed:#"7segvv.png"];
tresON = [UIImage imageNamed:#"7segvv.png"];
cuatroON =[UIImage imageNamed:#"7segvh.png"];
cincoON = [UIImage imageNamed:#"7segvh.png"];
seisON = [UIImage imageNamed:#"7segvv.png"];
sieteON = [UIImage imageNamed:#"7segvh.png"];
_uno = [[UIImageView alloc]initWithImage:unoOFF];
_dos = [[UIImageView alloc]initWithImage:dosOFF];
_tres = [[UIImageView alloc]initWithImage:tresOFF];
_cuatro = [[UIImageView alloc]initWithImage:cuatroOFF];
_cinco = [[UIImageView alloc]initWithImage:cincoOFF];
_seis = [[UIImageView alloc]initWithImage:seisOFF];
_siete = [[UIImageView alloc]initWithImage:sieteOFF];
//BLEViewController *myBLE = [[BLEViewController alloc]init];
//BLE *myBLE = [BLEViewController theBLEObject];
//NSLog(#"%#", myBLE.myData);
BLEViewController *myBLE = [[BLEViewController alloc]init];
myBLE.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark Delegado de Actualizar datos
-(void) actualizaDatos :(NSData *)myData{
NSLog(#"Datos recividos");
NSLog(#"Imprimio mi data con exitos %#", myData);
}
#end
In a nutshell, your BLEViewController is setting its delegate property to "self" when I think you want it to get set to an instance of "sevenSegmentsViewController". As a result the "if([delegate respondsToSelector:..." test is failing and you are never hitting the call to actualizaDatos. If you are using protocols correctly, you don't really need to test for "respondsToSelector" because by definition, the delegate must support the protocol.
The compiler and IDE are not showing you the error because you declared the property of the BLEViewController as just type "id" instead of
id<EnviarDatos>
If you fix the property declaration to say that your delegate must support the right protocol, you'll immediately see the errors highlighted.
hi i'm creating my own customized ComboBox, i copy on here my code so that anyone can use it. ( i don't know where else to put it lol )
I'd like also to know if you have better idea to improve it.
I get a small error, when i init the instance with the initWithBlurredImage, everything works fine but the blurred image doesn't cover the whole screen, it misses a small frame of about 5px. can you understand why?
//
// UIComboBox.h
// testComboBox
//
// Created by StabiloCode on 09/09/13.
// Copyright (c) 2013 SimplyXcode. All rights reserved.
//
#import <UIKit/UIKit.h>
#interface UIComboBox : UIViewController <UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource> {
UITextField *myTextField;
UIImageView *imageView;
UIPickerView *pickerView;
NSMutableArray *array;
UIToolbar *toolBar;
CGRect oldFrame;
UIImage *blurImage;
UIImageView *backgroundView;
}
#property (nonatomic, retain) UITextField *myTextField;
#property (nonatomic, retain) UIImageView *imageView;
#property (nonatomic, retain) UIPickerView *pickerView;
#property (nonatomic, retain) NSMutableArray *array;
#property (nonatomic, retain) UIImage *blurImage;
-(void)comboBox:(UIComboBox *)comboBox dataSource:(NSMutableArray *)anArray;
-(UIImage *)createBlur;
-(id)initwithBlurredImage:(UIImage *)anImage;
#end
//
// UIComboBox.m
// testComboBox
//
// Created by StabiloCode on 09/09/13.
// Copyright (c) 2013 SimplyXcode. All rights reserved.
//
#import "UIComboBox.h"
#interface UIComboBox ()
#end
#implementation UIComboBox
#synthesize myTextField, imageView, array, pickerView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
-(id)init {
self = [super init];
if ( self ){
}
return self;
}
-(id)initwithBlurredImage:(UIImage *)anImage{
blurImage = anImage;
NSLog(#"blur = %#",blurImage);
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
myTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 30)];
[myTextField setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:myTextField];
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(myTextField.frame.size.width-20, myTextField.frame.size.height-17, 25, 25)];
UIImage *arrow = [UIImage imageNamed:#"arrow.png"];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.clipsToBounds = YES;
[imageView setImage:arrow];
[self.view addSubview:imageView];
[myTextField setDelegate:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
[self showPickerView];
}
-(void)showPickerView{
//saving old frame to fix the position after the selection
oldFrame = self.view.frame;
//changing the frame to have the whole screen for the comboBox
[self.view setFrame:CGRectMake(0, 0, 320, 460)];
if(blurImage){
backgroundView = [[UIImageView alloc] initWithImage:blurImage];
backgroundView.backgroundColor = [UIColor colorWithPatternImage:blurImage];
[backgroundView setFrame:CGRectMake(0,0, 320, 460)];
[backgroundView setContentMode:UIViewContentModeScaleToFill];
[self.view addSubview:backgroundView];
[self.view sendSubviewToBack:backgroundView];
}
if ([myTextField.text isEqual: #""]){
myTextField.text = [array objectAtIndex:0];
}
[myTextField setEnabled:NO];
//creating the pickerview
pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 244, 320, 216)];
[pickerView setDataSource:self];
[pickerView setDelegate:self];
[pickerView showsSelectionIndicator];
[pickerView setShowsSelectionIndicator:YES];
[self.view addSubview:pickerView];
toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 200, 320, 244)];
toolBar.barStyle = UIBarStyleBlackTranslucent;
[toolBar sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(cancel)];
UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolBar setItems:#[space,cancelButton, doneButton]];
[self.view addSubview:toolBar];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [array objectAtIndex:row];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ return 1; }
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [array count];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
myTextField.text = [array objectAtIndex:row];
}
-(void)done{
[toolBar removeFromSuperview];
[pickerView removeFromSuperview];
[myTextField setEnabled:YES];
[self.view setFrame:oldFrame];
if(blurImage){ [backgroundView removeFromSuperview]; }
}
-(void)cancel{
myTextField.text = #"";
[toolBar removeFromSuperview];
[pickerView removeFromSuperview];
[myTextField setEnabled:YES];
[self.view setFrame:oldFrame];
if(blurImage){ [backgroundView removeFromSuperview]; }
}
// setting the pickerView content
-(void)comboBox:(UIComboBox *)comboBox dataSource:(NSMutableArray *)anArray{
self.array = anArray;
}
#end
if you want to use the code, you're free to do that, just let me know if it works fine :) stabilocode#gmail.com
I wrote a nice gallery view controller .h .m and .xib that work fine for my purposes. Tap a programmatically created button and load an image, play a movie or view a pdf or website - while in an existing uinavigationcontroller. I want to change it so I can add the contents of the xib in code - without using the nib file. In this way it will be more useable (I think).
The problem is the functions in the .m that reference, for instance - [self presentMoviePlayerViewControllerAnimated:YES] etc do not work. I tried making a property of the rootviewcontroller in this new .h and .m and replacing self with myController (property name). But my view controller code relies on uinavigation existing to push new content or things like that. How can I remove/tweak these references to self or a reliance on uinavigationcontrollers so it will work like when it has a view controller for a nib?
Edit: Code added below. In the nib there is just a uiscrollview called uis_thumbScrollView. I would like to add this anywhere by simply calling something like:
[self.view addSubview:[[ebThumbScroller alloc] initWithFrame:CGRectMake(0, 0, 1024, 733)]];
Everyone's comments reminded me that the uiview this will be put in exists within the rootviewcontroller, over the top. Maybe this is why I can hear the movie playing - but not see it.
Note: The code creates a series of uiviews with buttons inside of a uiscrollview.
.h
#import
#import "ebAppDelegate.h"
#import "MediaPlayer/MediaPlayer.h"
#interface HomeGalleryViewController : UIViewController <UIScrollViewDelegate, UIGestureRecognizerDelegate, UIDocumentInteractionControllerDelegate> {
BOOL pageControlBeingUsed;
int buttonCount;
CGFloat _minimumColumnGap;
UIEdgeInsets _contentInsets;
NSInteger _colCount;
NSInteger _rowCount;
CGFloat _rowGap;
CGFloat _colGap;
UIEdgeInsets _effectiveInsets;
//int iGalleryThumbs;
//int iPlanThumbs;
int iTotalButtons;
ebAppDelegate *ebappdelegate;
ebGalleryItem *ebgalleryItem;
NSDictionary *gallDict;
NSArray *gallerySections;
NSArray *galleryArray;
NSMutableArray *nsm_gallArray;
UIDocumentInteractionController *controller;
}
//#property (nonatomic, retain) IBOutlet UIButton *bItem;
#property (nonatomic, retain) NSString *galleryNameString;
#property (nonatomic, retain) IBOutlet UIScrollView* scrollView;
#property (retain, nonatomic) NSMutableArray *arr_Views;
#property (strong, nonatomic) IBOutlet UIScrollView* uis_thumbScrollView;
#property (strong, nonatomic) IBOutlet UIPageControl* uis_pageControl;
#property (strong, nonatomic) IBOutlet UIView *uiv_thumbView;
#property (strong, nonatomic) MPMoviePlayerController *player;
#property (strong, nonatomic) MPMoviePlayerViewController *playerViewController;
- (IBAction)changePage;
- (IBAction) clickOpen:(id)sender;
- (void)playMovie:(NSString*)movieName;
- (void)movieFinishedCallback:(NSNotification*)_notification;
#end
.m
#import "HomeGalleryViewController.h"
#import "ebAppDelegate.h"
#import "GalleryImagesViewController.h"
#import "Gallery.h"
#import "GalleryThumbnailsViewController.h"
#import "GalleriesListViewController.h"
#import <QuartzCore/CoreAnimation.h>
#import "ebGalleryItem.h"
#import "WebViewController.h"
#implementation HomeGalleryViewController
// buttons
#define hGutter 17
#define vGutter 13
#define btnSize 130
#define topSpace 50
#define leftMargin 100
#synthesize uiv_thumbView;
#synthesize uiv_gallCat0, uiv_gallCat1, uiv_gallCat2,uiv_gallCat3, uiv_gallCat4, uiv_gallCat5,uiv_gallCat6;
#synthesize uis_thumbScrollView, uis_pageControl;
#synthesize galleryNameString,scrollView,arr_Views;
#synthesize player, playerViewController;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
ebappdelegate = (ebAppDelegate *)[[UIApplication sharedApplication] delegate];
arr_Views = [[NSMutableArray alloc] init];
self.scrollView.contentSize = CGSizeMake(1024, 1005);
// nsarray of dictionaries (galleries)
gallerySections = ebappdelegate.arr_galleryData;
NSLog(#"gallerySections count:%i",[gallerySections count]);
nsm_gallArray = [NSMutableArray arrayWithCapacity:1];
[self layoutGalleryThumbs];
}
#pragma mark
#pragma mark Layout Gallery Thumbs
-(void)layoutGalleryThumbs {
NSUInteger numGallSections = [gallerySections count];
NSLog(#"gallerySections data:%#",gallerySections);
NSLog(#"numGallSections count:%i",numGallSections);
// Window bounds.
CGRect bounds = CGRectMake(0, 0, 1024, 215);
for (int i=0; i<numGallSections; i++) {
// Create a view and add it to the window.
UIView* vview = [[UIView alloc] initWithFrame: CGRectMake(0, bounds.size.height*i-1, bounds.size.width, bounds.size.height)];
[vview setBackgroundColor: [UIColor whiteColor]];
[vview setTag:i];
//vview.backgroundColor = (UIColor (i % 2 == 0 ? cyanColor : whiteColor];
vview.backgroundColor = (i % 2 == 0)? [UIColor lightGrayColor] : [UIColor whiteColor];
[arr_Views addObject:vview];
// add line below at bottom
UIView* lineView = [[UIView alloc] initWithFrame: CGRectMake(280, bounds.size.height, 700, 2)];
[lineView setBackgroundColor: [UIColor grayColor]];
lineView.alpha = 0.5;
[vview addSubview:lineView];
[uis_thumbScrollView addSubview: vview];
NSLog(#"start===============i:%i",i);
// grab a gallery
gallDict = [gallerySections objectAtIndex:i]; // grab dict
galleryArray = [gallDict objectForKey:#"gallSectionData"]; // grab array from dict
NSLog(#"galleryArray:%#",[galleryArray description]);
NSString *secTitle = [gallDict objectForKey:#"gallSectionName"];
iTotalButtons = [galleryArray count];
NSLog(#"iTotalButtons count:%i",iTotalButtons);
_minimumColumnGap = 5;
_colCount = floorf((uis_thumbScrollView.bounds.size.width - _contentInsets.left - _contentInsets.right) / btnSize);
while (1) {
_colGap = (uis_thumbScrollView.bounds.size.width - _contentInsets.left - _contentInsets.right - btnSize * _colCount) / (_colCount + 1);
if (_colGap >= _minimumColumnGap)
break;
--_colCount;
};
_rowCount = (iTotalButtons + _colCount - 1) / _colCount;
_rowGap = _colGap;
_effectiveInsets = UIEdgeInsetsMake(_contentInsets.top + _rowGap,
_contentInsets.left + _colGap,
_contentInsets.bottom + _rowGap,
_contentInsets.right + _colGap);
NSLog(#"row count:%i",_rowCount);
NSLog(#"col count:%i",_colCount);
buttonCount=0;
for (int e=0; e<iTotalButtons; e++) {
NSLog(#"e:%i",e);
ebgalleryItem = [galleryArray objectAtIndex:e];
UIImage *thumbImg = [UIImage imageNamed:ebgalleryItem.gallThumb];
UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
CGRect frame = CGRectMake (btnSize*e+leftMargin, topSpace,
btnSize-hGutter, btnSize-vGutter );
[button setFrame: frame];
NSLog(#"added button");
//[button setBackgroundImage:thumbImg forState:UIControlStateNormal];
[button setImage:thumbImg forState:UIControlStateNormal];
[button setTitle:ebgalleryItem.gallName forState:UIControlStateNormal];
NSLog(#"%#",button.titleLabel.text);
[button addTarget: NULL action:#selector(clickOpen:) forControlEvents:UIControlEventTouchUpInside];
UILongPressGestureRecognizer *tapAndHold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longclickOpen:)];
[tapAndHold setMinimumPressDuration:0.33];
[button addGestureRecognizer:tapAndHold];
[button setTag:e];
//[button setTag:i*_colCount+e];
NSLog(#" button tag=%i", button.tag);
button.alpha=1.0;
[[arr_Views objectAtIndex:i] addSubview:button];
NSLog(#"middle====i:%i",i);
// caption label
CGRect labelFrame = CGRectMake( btnSize*e+leftMargin, 125,
btnSize-hGutter, btnSize-vGutter );
UILabel* label = [[UILabel alloc] initWithFrame: labelFrame];
[label setFont:[UIFont fontWithName:#"Arial" size:14]];
label.numberOfLines = 0;
[label setText:ebgalleryItem.gallCaption];
[label setTextColor: [UIColor blackColor]];
[label setTextAlignment:UITextAlignmentCenter];
[label setBackgroundColor:[UIColor clearColor]];
[[arr_Views objectAtIndex:i] addSubview: label];
NSLog(#"middle2====i:%i",i);
buttonCount++;
}
// Section Title label
CGRect titleLabelFrame = CGRectMake(btnSize,0,250,50);
UILabel* titlelabel = [[UILabel alloc] initWithFrame: titleLabelFrame];
[titlelabel setFont:[UIFont fontWithName:#"Arial" size:16]];
[titlelabel setText:secTitle];
[titlelabel setTextColor: [UIColor blackColor]];
[titlelabel setTextAlignment:UITextAlignmentLeft];
[titlelabel setBackgroundColor:[UIColor clearColor]];
[[arr_Views objectAtIndex:i] addSubview: titlelabel];
NSLog(#"end====i:%i",i);
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in self.uis_thumbScrollView.subviews)
{
if (!view.hidden)
{
CGFloat y = view.frame.origin.y;
CGFloat h = view.frame.size.height;
if (y + h > scrollViewHeight)
{
scrollViewHeight = h + y;
}
}
}
[self.uis_thumbScrollView setContentSize:(CGSizeMake(self.uis_thumbScrollView.frame.size.width, scrollViewHeight+74))]; //74 is space from top in IB of scroll
}
uiv_thumbView.alpha = 1.0;
}
#pragma mark Scrollview
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.uis_thumbScrollView.frame.size.width;
int page = floor((self.uis_thumbScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.uis_pageControl.currentPage = page;
// nslogs zoomsacle/bounds
CGRect visibleRect;
visibleRect.origin = uis_thumbScrollView.contentOffset;
visibleRect.size = uis_thumbScrollView.bounds.size;
float theScale = 1.0 / [uis_thumbScrollView zoomScale];
visibleRect.origin.x *= theScale;
visibleRect.origin.y *= theScale;
visibleRect.size.width *= theScale;
visibleRect.size.height *= theScale;
NSLog( #"Visible rect: %#", NSStringFromCGRect(visibleRect) );
}
- (IBAction)changePage {
// update the scroll view to the appropriate page
CGRect frame;
frame.origin.x = self.uis_thumbScrollView.frame.size.width * self.uis_pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.uis_thumbScrollView.frame.size;
[self.uis_thumbScrollView scrollRectToVisible:frame animated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
//===================================================================
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft | interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (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 {
[self setUiv_thumbView:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (void)viewWillAppear:(BOOL)animated {
[UIApplication sharedApplication].statusBarHidden = YES;
self.view.frame = [UIScreen mainScreen].applicationFrame;
CGRect frame = self.navigationController.navigationBar.frame;
frame.origin.y = 0;
self.navigationController.navigationBar.frame = frame;
[self.navigationController setNavigationBarHidden:YES animated:animated];
self.navigationController.navigationBar.translucent = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[UIApplication sharedApplication].statusBarHidden = NO;
CGRect frame = self.navigationController.navigationBar.frame;
frame.origin.y = 20.0;
self.navigationController.navigationBar.frame = frame;
}
- (void)viewDidAppear:(BOOL)animated {
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[self.navigationController setNavigationBarHidden:YES animated:animated];
[self.navigationController setToolbarHidden:YES animated:YES];
[super viewDidAppear:animated];
}
//======================================================================
-(IBAction)clickOpen:(id)sender {
UIButton *tmpBtn = (UIButton*)sender;
NSLog(#"sender tag: %i", [sender tag]);
int superviewTag = [sender superview].tag;
NSLog(#"sender superview tag: %i", superviewTag);
gallDict = [gallerySections objectAtIndex:superviewTag]; // grab dict
galleryArray = [gallDict objectForKey:#"gallSectionData"]; // grab array from dict
tmpBtn.alpha = 0.6;
ebgalleryItem = [galleryArray objectAtIndex:[sender tag]];
NSLog(#"%#",ebgalleryItem.gallType);
NSLog(#"%#",ebgalleryItem.gallName);
NSLog(#"gallDict %#",gallDict);
if ([ebgalleryItem.gallType isEqualToString:#"movie"]) {
[self playMovie:ebgalleryItem.gallFilm];
} else if ([ebgalleryItem.gallType isEqualToString:#"image"]) {
[self imageViewer:sender];
} else if ([ebgalleryItem.gallType isEqualToString:#"pdf"]) {
[self viewPDF:ebgalleryItem.gallName];
} else if ([ebgalleryItem.gallType isEqualToString:#"web"]) {
[self openWeb:ebgalleryItem.gallName];
}
}
#pragma mark
#pragma mark Open Websites
- (IBAction)openWeb:(NSString*)thisWEB {
WebViewController *webViewController = [[WebViewController alloc]
initWithNibName:#"WebViewController"
bundle:nil];
[webViewController socialButton:thisWEB];
webViewController.title = thisWEB;
[self presentModalViewController:webViewController animated:YES];
}
#pragma mark
#pragma mark Image Viewer
-(void)imageViewer:(id)sender {
UIButton *tmpBtn = (UIButton*)sender;
galleryNameString = tmpBtn.titleLabel.text;
tmpBtn.alpha = 0.6;
GalleryImagesViewController *vc = [[GalleryImagesViewController alloc] initWithGallery:[Gallery galleryNamed:galleryNameString]];
[vc goToPageAtIndex:0 animated:NO];
CATransition* transition = [CATransition animation];
transition.duration = 0.33;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromTop;
[self.navigationController.view.layer
addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:vc animated:NO];
}
#pragma mark
#pragma mark PDF Viewer
-(void)viewPDF:(NSString*)thisPDF {
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:thisPDF ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:fileToOpen];
NSLog(#"%#",fileToOpen);
controller = [UIDocumentInteractionController interactionControllerWithURL:url];
[self previewDocumentWithURL:url];
}
- (IBAction) clickClose:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}
- (void)previewDocumentWithURL:(NSURL*)url
{
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
}
//======================================================================
- (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller{
}
//===================================================================
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
return self.view.frame;
}
-(IBAction)longclickOpen:(UILongPressGestureRecognizer*)gesture {
if (gesture.state == UIGestureRecognizerStateBegan ) {
[self.navigationController setNavigationBarHidden:NO];
ebAppDelegate *appDelegate = (ebAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.isFromLongPress=YES;
//NSUInteger i = [gesture.view tag];
//galleryNameString = [appDelegate.arr_galleryData objectAtIndex:i];
NSLog(#"load %#",galleryNameString);
UIButton *btn = (UIButton*)gesture.view;
galleryNameString = btn.titleLabel.text; btn.alpha = 0.6;
//NSLog(#"Long Press");
//NSLog(#"llongclickOpen");
UIViewController *vc = [[GalleryThumbnailsViewController alloc] initWithGallery:[Gallery galleryNamed:galleryNameString]];
CATransition* transition = [CATransition animation];
transition.duration = 0.33;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromTop;
[self.navigationController.view.layer
addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:vc animated:NO];
}
}
-(void)playMovie:(NSString*)movieName {
NSString *url = [[NSBundle mainBundle]
pathForResource:movieName
ofType:#"m4v"];
NSLog(#"%#",movieName);
playerViewController = [[MPMoviePlayerViewController alloc]
initWithContentURL:[NSURL fileURLWithPath:url]];
[[NSNotificationCenter defaultCenter] removeObserver:playerViewController
name:MPMoviePlayerPlaybackDidFinishNotification
object:playerViewController.moviePlayer];
// Register this class as an observer instead
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:playerViewController.moviePlayer];
[self.view insertSubview:playerViewController.view atIndex:50];
//---play movie---
player = [playerViewController moviePlayer];
player.controlStyle = MPMovieControlStyleFullscreen;
player.repeatMode=MPMovieRepeatModeOne;
[self presentMoviePlayerViewControllerAnimated:playerViewController];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[super viewDidLoad];
}
- (void)movieFinishedCallback:(NSNotification*)aNotification {
// Obtain the reason why the movie playback finished
NSNumber *finishReason = [[aNotification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
// Dismiss the view controller ONLY when the reason is not "playback ended"
if ([finishReason intValue] != MPMovieFinishReasonPlaybackEnded)
{
MPMoviePlayerController *moviePlayer = [aNotification object];
// Remove this class from the observers
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
// Dismiss the view controller
[self dismissModalViewControllerAnimated:YES];
}
}
#end
If your only problem is the not working [self presentMoviePlayerViewControllerAnimated:YES] method, the problem is that presentMoviePlayerViewControllerAnimated: requires the actual moviePlayerViewController as an argument not a boolean value. (assuming you're refering to this method of the UIViewController category) UIViewController MediaPlayer Additions Reference
So if you replace that by say presentMoviePlayerViewControllerAnimated:self.moviePlayerVC, it should work as expected.
I'm not sure I understand your question, but if you need to wrap your controller to some UINavigationController you can do it like this:
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myController];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.navigationBar.barStyle = UIBarStyleBlack;
[self presentViewController:navController animated:YES completion:^{
//
}];
later on any child controller will have the navigation hierarchy.