I am trying to make an application that counts the number of clicks on a button, and plays a sound when the number of clicks is 10 ... I've tried a lot of different code, but it's not working. Any help is appreciated.
This is the .m file
What should I add inside the if statement?
#import "ViewController.h"
#import "AVFoundation/AVAudioPlayer.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)Add{
count++;
number.text =[NSString stringWithFormat:#"%i", count];
if (count==10) {
}
}
-(IBAction)Reset{
count=0;
number.text =[NSString stringWithFormat:#"%i", count];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And this is the .h file
#import <UIKit/UIKit.h>
int count;
#interface ViewController : UIViewController
{
IBOutlet UILabel *number;
}
-(IBAction)Add;
-(IBAction)Reset;
#end
Related
I'm reading the Big Nerd Ranch book and I'm at the 10th chapter about the navigation controller.
In the main controller, there is a TableView ( https://github.com/bignerdranch/iOS3eSolutions/blob/master/11.%20Homepwner/Homepwner/Homepwner/ItemsViewController.m ) where there are two methods that interact with the detail view :
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[self tableView] reloadData];
}
- (void)tableView:(UITableView *)aTableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
NSArray *items = [[BNRItemStore sharedStore] allItems];
BNRItem *selectedItem = [items objectAtIndex:[indexPath row]];
// Give detail view controller a pointer to the item object in row
[detailViewController setItem:selectedItem];
// Push it onto the top of the navigation controller's stack
[[self navigationController] pushViewController:detailViewController
animated:YES];
}
In the detail view controller (https://github.com/bignerdranch/iOS3eSolutions/blob/master/11.%20Homepwner/Homepwner/Homepwner/DetailViewController.m), there is a method that "saves" the BNRItem being changed :
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Clear first responder
[[self view] endEditing:YES];
// "Save" changes to item
[item setItemName:[nameField text]];
[item setSerialNumber:[serialNumberField text]];
[item setValueInDollars:[[valueField text] intValue]];
}
The code works well :
I understand how the main controller set the object to edit but I don't understand how the main view controller knows that the BNRItem has been changed and then set it back to the tableview ?
I was excepting the author to write a setter in the main controller (ItemsViewController.m ) that could be called by the detail view controller (DetailViewController.m) giving the new BNRItem.
But this part works "automatically".
Thank you.
As you are pointing to the same memory chunk in both controllers, changed made in the DetailViewController are obviously reported in ItemsViewController.m.
I am using core data and am trying to add table view cells to a table view in a view controller. When I implement it in a table view controller the app runs. When I run it when the table view is part of another view controller, the app does not run. It shows an error in the code: property tableview not found on object of type DeviceViewController. DeviceViewController.h has a table view data source and delegate. My code is:
#import "DeviceViewController.h"
#import "DeviceDetailViewController.h"
#interface DeviceViewController ()
#property (strong) NSMutableArray *devices;
#end
#implementation DeviceViewController
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Device"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.devices.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%# ", [device valueForKey:#"name"]]];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[self.devices objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.devices removeObjectAtIndex:indexPath.row];
[self. otableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
As I see it, in this case, it has nothing to do with CoreData.
You should add the UITableViewDataSource and UITableViewDelegate protocols to your VC.
After that you should create a UITableView (you can do it in interface builder) and connect the datasource and delegate to your view controller.
You can also add a property for the UITableView in your VC.
When you use UITableViewController, all this is done from Xcode, but if you use UITableView inside a regular UIViewController you should take care of this stuff.
Good Luck!
EDIT:
Add this as a propert
#property (nonatomic, strong) UITableView *deviceTableView;
Change the viewDidLoad method to this:
- (void)viewDidLoad {
[super viewDidLoad];
_deviceTableView = [[UITableView alloc] initWithFrame:self.view.frame];
_deviceTableView.delegate = self;
_deviceTableView.dataSource = self;
[self.view addSubview:_deviceTableView];
[_deviceTableView reloadData];
}
Delete what you have written in viewDidAppear and replace self.tableView with _deviceTableView everywhere in this file.
Another problem that could be causing the crashes is if your NSManagedObjectContext is nil when you are trying to execute the fetch request. I would add an if([self managedObjectContext])
before using it in any of your view hierarchy methods.
Also, you should be careful when using views instantiated from storyboards. Nikola's answer said to add the code configuring the view controller in viewDidLoad, and that is ok as long as you did not drag a UITableView onto your UIViewController instance in interface builder. If you already have created and linked a tableview in interface builder, you will be needlessly replacing it with a new one, so before the
_deviceTableView = [[UITableView alloc] initWithFrame:self.view.frame];
line, you should add an if(!_deviceTableView)
statement because it will prevent you from adding a second table view to your view. The issue is that if you have already added a tableview in IB, it will be retained by your view even after you change your tableview property, so it is possible to have two tables show up.
Alternatively, you could use "lazy instantiation" in your getter method for the table view property to make sure it is initialized when you access it.
Lastly, in order to help give us a better idea of why your app is crashing it would be helpful to get the exception log from the console in Xcode.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am new to iOS, i am using Xcode 4.3.2, and i have created a project with tabView, where by default it has two view controllers. I am creating a new one now,
ThirdView.h
#import <UIKit/UIKit.h>
#interface ThirdView : UIViewController
#end
#import "ThirdView.h"
#implementation ThirdView
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Third", #"Third");
self.tabBarItem.image = [UIImage imageNamed:#"Third"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
and in the appDelicate.m
viewController3 = [[ThirdView alloc] initWithNibName:#"ThirdView" bundle:nil];
and added viewController3 to tabBarController.
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3 ,nil];
The Problem is:
When i execute the code in the device, i could see the third tab, but the moment i click, it crashes.
Where i am doing wrong ?
Double check the class name of the third view controller in you nib file.
I have an app which adds a webview as a subview of the main UIViewController. I want to intercept the links clicked in this webview and open them in a new UIViewController (as modal view or navigationController).
For this new UIViewController, i am using https://github.com/samvermette/SVWebViewController which is an inline browser class and works pretty well.
I am able to intercept clicks from that webview just fine in webView:shouldStartLoadWithRequest:navigationType. But my problem is that it is not able to open the new UIViewController (SVWebViewController). Following is the code to intercept clicks in the webView and open it :
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if(inType == UIWebViewNavigationTypeLinkClicked) {
NSURL *url = [inRequest URL];
NSString *fname = [url absoluteString];
SVWebViewController *webViewController = [[SVWebViewController alloc] initWithAddress:fname];
[self presentModalViewController:webViewController animated:YES];
[webViewController release];
return NO;
}
return YES;
}
There is no issue in SVWebViewController, it works fine when i call it from the main UIView but not when i use it to open clicks from the webView.
Thanks for your help!!
i used this code to detect touch on an uiscrollview who is on top of uiview
subclass
.h file
#interface AppScrollView : UIScrollView
{
}
#end
.m file
#import "AppScrollView.h"
#implementation AppScrollView
- (id)initWithFrame:(CGRect)frame
{
return [super initWithFrame:frame];
}
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
// If not dragging, send event to next responder
if (!self.dragging)
[self.nextResponder touchesEnded: touches withEvent:event];
else
[super touchesEnded: touches withEvent: event];
}
#end
and then on another class i added
#import <UIKit/UIKit.h>
#class AppScrollView;
#interface SomeClass : UIViewController <UIScrollViewDelegate>
{
AppScrollView *scrollView;
...
}
#end
#import "AppScrollView.h"
#implementation SomeClass
...
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
// Process the single tap here
...
}
...
#end
i used also scroll1.delegate=self; but nothing happens!!!
Can anyone help me?
Use Gesture Recognizers. Specifically UITapGestureRecognizer.