Increment UISlider by 1 in range 1 to 100 - ios

I am new to iPhone,
How do I have my UISlider go from 1 to 100 in increments of 1?
slider = [[UISlider alloc] init];
[slider addTarget:self action:#selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
slider.value = 0.0;
- (IBAction)sliderChange:(id)sender{
NSLog(#"slider.value=%f",slider.value);
}
When i slide my log shows...
slider.value = 1.000000
slider.value = 1.123440
slider.value = 1.234550
slider.value = 1.345670
slider.value = 1.567890
.
.
.
I want slider value as 1.0 , 2.0 , 3.0 and so on...

//Only generate update events on release
slider.continuous = NO;
//Round the value and set the slider
- (IBAction)sliderChange:(id)sender
{
int rounded = sender.value; //Casting to an int will truncate, round down
[sender setValue:rounded animated:NO];
NSLog(#"%f", sender.value);
}

you could try this:
float RoundValue(UISlider * slider) {
return roundf(slider.value * 2.0) * 1;
}

yourSlider.minimumValue = 1;
yourSlider.maximumValue = 100;
[yourSlider addTarget:self action:#selector(roundValue) forControlEvents:UIControlEventValueChanged];
- (void)roundValue{
yourSlider.value = round(yourSlider.value);
}
also see this bellow answer helpful toy you,give some idea...
UISlider increments
and also another which may give you some idea..
UISlider with increments of 5

I know i'm late to the party but I've also had to do this recently. Here is how I've done it in swift using XCode 8.3.2:
#IBAction func sliderValueChanged(_ slider: UISlider) {
label.text = Int(slider.value)
}
Simples! I know I could have used 'Any' instead of 'UISlider', but I think this makes my intention clearer ;)

change
` NSLog(#"slider.value=%f",slider.value);`
to
NSLog(#"slider.value=%.f",slider.value);
if you want one digit then :
NSLog(#"slider.value=%.0f",slider.value);
but this will give you results like 1.0,1.1,....

Here is simple Example of UISlider
headereFile.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UIScrollViewDelegate,UITextFieldDelegate>
{
IBOutlet UISlider *slider;
IBOutlet UILabel *lbl;
IBOutlet UITextField *txtField;
IBOutlet UIButton *btn;
IBOutlet UISwitch *swich;
IBOutlet UIScrollView *scView;
}
#property(nonatomic,retain)UISlider *slider;
#property(nonatomic,retain)UILabel *lbl;
#property(nonatomic,retain)UITextField *txtField;
#property(nonatomic,retain)UIButton *btn;
#property(nonatomic,retain)UIScrollView *scView;
#property(nonatomic,retain)UISwitch *swich;
-(IBAction)sliderChanged:(UISlider *)slider;
-(IBAction)ButtonPressed:(id)sender;
-(IBAction)showTextField:(id)sender;
#end
implementFile.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize slider,lbl,txtField,btn,scView,swich;
- (void)viewDidLoad
{
self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
self.scView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,320,460)];
self.scView.delegate=self;
self.scView.contentSize=CGSizeMake(320,465);
[self.view addSubview:self.scView];
self.slider=[[UISlider alloc] initWithFrame:CGRectMake(50,270,220,30)];
self.slider.minimumValue=0.00;
self.slider.maximumValue=100.00;
self.slider.thumbTintColor=[UIColor redColor];
[self.slider addTarget:self action:#selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
[self.scView addSubview:self.slider];
self.lbl=[[UILabel alloc] initWithFrame:CGRectMake(135, 290,200,30)];
self.lbl.backgroundColor=[UIColor clearColor];
NSString *str=[NSString stringWithFormat:#"%.f",[self.slider value]];
self.lbl.text=str;
[self.scView addSubview:self.lbl];
self.txtField=[[UITextField alloc] initWithFrame:CGRectMake(50, 220,150,30)];
self.txtField.borderStyle=UITextBorderStyleRoundedRect;
self.txtField.delegate=self;
self.txtField.returnKeyType=UIReturnKeyDone;
self.txtField.placeholder=#"Enter 1 to 100";
[self.scView addSubview:self.txtField];
self.btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
self.btn.frame=CGRectMake(205, 215,64, 37);
[self.btn setTitle:#"Change" forState:UIControlStateNormal];
[self.btn addTarget:self action:#selector(ButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.scView addSubview:self.btn];
self.swich=[[UISwitch alloc] initWithFrame:CGRectMake(124,140, 75,40)];
[self.swich addTarget:self action:#selector(showTextField:) forControlEvents:UIControlEventValueChanged];
self.swich.on=YES;
/*
((UILabel *)[[[[[[self.swich subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:0]).text = #"Foo";
((UILabel *)[[[[[[self.swich subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:1]).text = #"Bar";
*/
[self.scView addSubview:self.swich];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)showTextField:(id)sender
{
if (self.swich.on)
{
[self.swich setOn:YES animated:YES];
self.txtField.hidden=NO;
self.btn.hidden=NO;
}
else
{
[self.swich setOn:NO animated:YES];
self.txtField.hidden=YES;
self.btn.hidden=YES;
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
self.scView.frame=CGRectMake(0, 0,320,230);
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[self.txtField resignFirstResponder];
self.scView.frame=CGRectMake(0, 0,320,460);
return YES;
}
-(IBAction)sliderChanged:(UISlider *)slider;
{
NSString *str=[NSString stringWithFormat:#"%.f",[self.slider value]];
self.lbl.text=str;
}
-(IBAction)ButtonPressed:(id)sender
{
NSString *values=[self.txtField text];
float Values=[values floatValue];
if (Values<=100)
{
self.slider.value=Values;
self.lbl.text=values;
}
else
{
UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:#"NSURLConnection " message:#"Plz...Entre Proper Value !!!" delegate: self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[connectFailMessage show];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end

I use this bit of code when I want the increment to be 0.5. It works with 1 or any other number
- (void) getSliderValue:(UISlider *)paramSender{
float increment = 0.5;
if ([paramSender isEqual:self.slider]){ //remove if you only have one slider
float newValue = paramSender.value /increment;
paramSender.value = floor(newValue) * increment;
}
NSLog(#"Current value of slider is %f", paramSender.value);
}

Related

Decrease size of UIButtons on Screen upon Pinch Gesture

I have couple of UIButtons on the screen. If a pinch gesture occurs, I want to decrease the size of the buttons (Like a zoom-out effect) and add more buttons. How would I implement it?
I am typing this directly on StackOverflow, so there may be typos.
These features are left as an exercise for the OP:
Cumulatively scaling down with successive pinches. You must have another private property to hold the current scale value.
Adding new buttons after the zooming out effect.
Code:
#interface MyViewController : UIViewController
#property(nonatomic, strong) NSMutableArray* buttons;
- (void)pinched:(UIPinchGestureRecognizer*)gesture;
#end
#implementation MyViewController
- (void)loadView {
[super loadView];
self.buttons = [NSMutableArray array];
for (NSUInteger i = 0; i < 3; i++) {
UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(
0.0f,
(44.0f + 10.0f) * (CGFloat)i,
100.0f,
44.0f
)];
button.backgroundColor = [UIColor blueColor];
[self.view addSubview:button];
[self.buttons addObject:button];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
UIPinchGestureRecognizer* pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(pinched:)];
[self.view addGestureRecognizer:pinch];
}
- (void)pinched:(UIPinchGestureRecognizer*)gesture {
if (gesture.scale > 1.0) {
return;
}
for (UIButton* button in self.buttons) {
[UIView
animateWithDuration:1.0
animations:^void() {
button.transform = CGAffineTransformMakeScale(0.5, 0.5);
}
];
}
}
#end

Xcode - IB elements not shown in my view at runtime

I've got a very weird problem with my iOS project.
I have a UIViewController with some labels and buttons and when user enters this view I programmatically build a gameboard (it's the minesweeper game).
What I wanted to do now is add a simple element (in my case a segmented control but i tried also with a button and doesn't work) at the bottom or at the beginning of the board.
When I add something from the Interface Builder I can see that in the storyboard but when I run the app puff, it's disappeared!
View contains only the "old" elements and the new one is not shown.
Yes I made a IBOutlet:
#property (weak, nonatomic) IBOutlet UISegmentedControl *clickTypeSegmentedControl;
And yes I checked if references of segemented control are ok.
I can't really understand what is wrong, if someone can help I'll be very grateful.
** EDIT: I added code of the ViewController, there are some other methods I left out because they only handle the game. I repeat: even if I add a simple button with no actions, it will not be shown.
#import "GameViewController.h"
#import "GameBoardModel.h"
#import "ScoreViewController.h"
#import <AVFoundation/AVFoundation.h>
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#interface GameViewController ()
#property (weak, nonatomic) IBOutlet UILabel *timerLabel;
#property (weak, nonatomic) IBOutlet UILabel *bombsLabel;
#property (weak, nonatomic) IBOutlet UIButton *restartButton;
#property(nonatomic, strong) AVAudioPlayer *soundEffects;
#property (weak, nonatomic) IBOutlet UISegmentedControl *clickTypeSegmentedControl;
#end
#implementation GameViewController
#synthesize difficulty, timer, playerName, scoreToAdd, clickTypeSegmentedControl;
double secondsPassed=-1.0f;
int seconds=0;
int totalRowsCols=0, totalMines=0, heightWidth=0, clicKNumber=0;
static NSString * const IMAGE_NAME_FLAG = #"flag.png";
static NSString * const IMAGE_NAME_BOMB_X = #"bomb.png";
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.hidesBackButton = YES;
UIBarButtonItem *backButton =[[UIBarButtonItem alloc]initWithTitle:#"MenĂ¹" style:UIBarButtonItemStyleBordered target:self action:#selector(popAlertAction:)];
self.navigationItem.leftBarButtonItem=backButton;
clickTypeSegmentedControl.selectedSegmentIndex = 0;
rootController = (BombsSeekerViewController *)[self.navigationController.viewControllers objectAtIndex:0];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
playerName = [defaults objectForKey:#"NomeGiocatore"];
scoreToAdd = [[NSMutableDictionary alloc]init];
[self createGameBoard:difficulty];
[self newGame:nil];
}
-(void) newGame:(UIButton *)sender {
[self.view.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
clicKNumber=0;
secondsPassed=0;
self.timerLabel.text = [self labelString:secondsPassed];
self.game = [[Game alloc] initWithWidth:totalRowsCols AndHeight:totalRowsCols AndMineCount:totalMines];
self.buttonArray = [[NSMutableArray alloc] init];
[self.restartButton addTarget:self action:#selector(newGame:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.restartButton];
[self.view addSubview:self.timerLabel];
[self.view addSubview:self.bombsLabel];
for(int i = 0; i < totalRowsCols; i++) {
for (int j = 0; j < totalRowsCols; j++) {
self.button = [[Tile alloc] initWithLocation: CGPointMake(j,i) andHW:heightWidth andBlock:self.game.board[j][i] andTag:(i*totalRowsCols+j)];
[self.buttonArray addObject:self.button];
[self.view addSubview:self.button];
[self.button addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
}
[self.timer invalidate];
}
- (void) createGameBoard:(int)diff{
switch (diff) {
case 1:
totalRowsCols = 6;
totalMines = 2;
heightWidth = 44;
break;
case 2:
totalRowsCols = 8;
totalMines = 16;
heightWidth = 35;
break;
case 3:
totalRowsCols = 10;
totalMines = 25;
heightWidth = 29;
break;
}
self.flagCount = totalMines;
_bombsLabel.text = [NSString stringWithFormat:#"%d",self.flagCount];
}
-(NSString *) labelString: (int) num {
if(num < 10) {
return [NSString stringWithFormat:#"00%i",num];
}
else if(self.timeCount.intValue < 100) {
return [NSString stringWithFormat:#"0%i",num];
}
else if(self.timeCount.intValue < 1000) {
return [NSString stringWithFormat:#"%i",num];
}
else
return #"---";
}
-(void) click:(Tile *)sender {
if(clicKNumber <1){
[self refreshLabel:self.timer];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(refreshLabel:)
userInfo:nil
repeats:YES];
clicKNumber++;
}
if(self.game.gameStatus == STATUS_LOST || self.game.gameStatus == STATUS_WON) return;
if (self.clickTypeSegmentedControl.selectedSegmentIndex == 0 && sender.block.marking == MARKING_BLANK) {
[self.game clickedAtColumn: sender.point.x AndRow: sender.point.y];
for(Tile *b in self.buttonArray) {
if(b.block.marking == MARKING_CLICKED) {
b.enabled = NO;
}
else if(b.block.marking == MARKING_BLANK) {
[b setTitle:#"" forState:UIControlStateNormal];
[b setImage:nil forState:UIControlStateNormal];
}
}
}
else if (self.clickTypeSegmentedControl.selectedSegmentIndex == 1){
if(sender.block.marking == MARKING_BLANK && self.flagCount > 0) {
sender.block.marking = MARKING_FLAGGED;
self.flagCount--;
_bombsLabel.text = [NSString stringWithFormat:#"%d",self.flagCount];
[sender setImage:[UIImage imageNamed:IMAGE_NAME_FLAG] forState:UIControlStateNormal];
}
else if(sender.block.marking == MARKING_FLAGGED) {
sender.block.marking = MARKING_BLANK;
self.flagCount++;
_bombsLabel.text = [NSString stringWithFormat:#"%d",self.flagCount];
[sender setImage:[UIImage imageNamed:#"tile.png"] forState:UIControlStateNormal];
}
}
if(self.game.gameStatus == STATUS_LOST) [self gameLost:sender];
else if(self.game.gameStatus == STATUS_WON) [self gameWon];
}
If this is what I think it is, you should not be doing this:
[self.view.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
When the viewDidLoad is called, the newGame method is called, which removes al subviews from Superview. Including the ones added in Storyboard.
Make sure controller in storyboard is linked with the right controller class.
You call this method during -viewDidLoad:
-(void) newGame:(UIButton *)sender {
[self.view.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
//...
}
Thus, anything you put in your nib is getting removed after it loads.

custom uitextfield with custom inputAccessoryView

is strange to se no question about this problem in all stack overflow, but i can't find it :(
So let me explain. I have a simple UITextField that should present a custom inputAccessoryView.
The expected behavior is:
tap in the textfield (ACTextField)
show keyboard with a textfield and a button (with cancel title)
type in some text (it have to appear in the UITextField named
inputField )
press enter and see the text appearing in the main textfield
in case i press cancel the keyboard should disappear and let the main textfield unchenged
pretty much like the Message App from Apple
And all works well exept 2 things:
if i spam key tapping on the keyboard (just to enter random text ;)
) the app freeze and Xcode show me CPU at 99% (no recovery possible)
sometimes the memory occupation grow from 2/3 MB to 40 MB just after
pressing enter and the app freeze again
Let's show some code
the .h
#import <UIKit/UIKit.h>
#interface ACTextField : UITextField
#end
the .m
#import "ACTextField.h"
#interface ACTextField () <UITextFieldDelegate>
#property (nonatomic, retain) UITextField *inputField;
#property (nonatomic, assign) BOOL keyboardOpen; // to check if keyboard is open
#property (nonatomic, retain) NSTimer *timer; //added after an answer
#end
#implementation ACTextField
// method called when timer fire
- (void) fireTimer:(NSTimer *) timer
{
[self.timer invalidate];
self.timer = nil; // this line thoesen't change anyting so can be deleted
[self.inputField becomeFirstResponder];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self awakeFromNib];
}
return self;
}
-(void)awakeFromNib
{
self.delegate = self;
self.keyboardOpen = NO;
}
- (void)cancelPressed:(id)sender
{
[self.inputField resignFirstResponder];
[self resignFirstResponder];
self.keyboardOpen = NO;
}
- (void)dealloc
{
NSLog(#"dealloc ACTextField %#", self);
self.inputField = nil;
self.timer = nil;
}
- (void) designAccessoryView
{
if (self.inputAccessoryView == nil) {
CGRect frame = [[UIScreen mainScreen] bounds];
self.inputAccessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 44)];
self.inputAccessoryView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
int buttonWidth = 65;
int padding = 5;
UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
cancel.frame = CGRectMake(padding, 0, buttonWidth, 44);
[cancel setTitle:#"cancel" forState:UIControlStateNormal];
[cancel setTitle:#"cancel" forState:UIControlStateHighlighted];
[cancel addTarget:self action:#selector(cancelPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.inputAccessoryView addSubview:cancel];
self.inputField = [[UITextField alloc] initWithFrame:CGRectMake(buttonWidth + 2*padding, 2, frame.size.width - buttonWidth - 3*padding, 40)];
self.inputField.borderStyle = UITextBorderStyleRoundedRect;
self.inputField.delegate = self;
[self.inputAccessoryView addSubview:self.inputField];
self.inputAccessoryView.backgroundColor = [UIColor lightGrayColor];
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if (!self.keyboardOpen && textField == self)
{
self.inputField.text = self.text;
[self designAccessoryView];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self // modified to use the instance method fireTimer
selector:#selector(fireTimer:)
userInfo:nil
repeats:NO];
self.keyboardOpen = YES;
}
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
self.text = self.inputField.text;
[self cancelPressed:self];
return YES;
}
#end
Any help will be greatly appreciated
EDIT: I forgot to specify that i'm testing this on my iPhone 4s with IOS 7.0.4
EDIT2: I tried using an UITextField Wrapper with pretty much the same code and all goes well. The behavior is the expected and the keyboard don't freeze anymore and the memory remain low as should be. Ok, but i need a UITextField subclass, not a wrapper :(

IBAction addTarget:action:forControlEvents: not working when touched for the first time, otherwise fine

I am developing a calculator app and I am trying to highlight touched buttons by changing the background color. My problem is that when I touch the button for the first time, it displays the numbers but the background color does not change. But later on it works fine, just the first touch does not work at all. I appreciate any help!
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#interface ViewController ()
#end
#implementation ViewController
#synthesize resultLabel;
BOOL isDecimal;
NSArray *array;
NSNumber *number;
NSNumberFormatter *formatter;
- (void)viewDidLoad
{
[super viewDidLoad];
array = [[NSArray alloc]initWithObjects:ACbuttonOutlet, deleteButtonOutlet, plusMinusOutlet, divideOutlet, number7Outlet, number8Outlet, number9Outlet, multiplicationOutlet, number4Outlet, number5Outlet, number6Outlet, plusOutlet, number1Outlet, number2Outlet, number3Outlet, minusOutlet, number0Outlet, decimalOutlet, resultOutlet, nil];
for(UIButton *button in array)
{
[button.layer setBorderWidth:0.25];
[button.layer setBorderColor:[UIColor blackColor].CGColor];
}
resultLabel.adjustsFontSizeToFitWidth = YES;
/*formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSize:3];
[formatter setGroupingSeparator:#" "];
number = [NSNumber numberWithInt:[resultLabel.text intValue]];
resultLabel.text = [formatter stringFromNumber:number];*/
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)highlightButton:(UIButton *)button
{
AudioServicesPlaySystemSound(0x450);
[button setBackgroundColor:[UIColor colorWithRed:239/255.0 green:232/255.0 blue:232/255.0 alpha:1]];
NSLog(#"1");
}
- (void)resetButtonBackGroundColor: (UIButton *)sender{
[sender setBackgroundColor:[UIColor whiteColor]];
NSLog(#"2");
}
- (IBAction)ACbutton:(id)sender {
[sender addTarget:self action:#selector(highlightButton:) forControlEvents:UIControlEventTouchDown];
[sender addTarget:self action:#selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];
isDecimal = NO;
Method = 0;
SelectNumber = 0;
RunningTotal = 0;
resultLabel.text = [NSString stringWithFormat:#"0"];
}
Try to add this line in viewDidLoad method into your cycle
for(UIButton *button in array)
{
[button.layer setBorderWidth:0.25];
[button.layer setBorderColor:[UIColor blackColor].CGColor];
[button addTarget:self action:#selector(highlightButton:) forControlEvents:UIControlEventTouchDown];
}
I would suggest you not to work upon background color of the button . Instead toggle/change the background image of the button.

Refactor iOS ViewController to work without needing a nib

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.

Resources