How to set text to UILabel from Button click in different views - ios

Hi everyone iam new in objective c, now i try to create the app like "What's the word". I find this tutorial and lerned it as well as i can. But i have some problems. I want when i click on buttons the currentTitle replace the lable in placesView. Button click method in LettersView.m named as "displayChar". I have success in getting currentTitle but now i don't know how to pass it to GameController and paste text on "places".
I will be grateful for any help!
Here is my code
LettersView.h
#import <UIKit/UIKit.h>
#class LettersView;
#protocol LetterClickDelegateProtocol <NSObject>
-(void)letterView:(LettersView*)letterView addChar:(NSString *)addChar;
#end
#interface LettersView : UIImageView
#property (strong, nonatomic, readonly) NSString* letter;
#property (assign, nonatomic) BOOL isMatched;
#property (strong, nonatomic) NSString *clickLetter;
#property (weak, nonatomic) id<LetterClickDelegateProtocol> clickDelegate;
#property (strong, nonatomic) UIButton *lblChar;
-(instancetype)initWithLetter:(NSString*)letter andSideLength:(float)sideLength;
#end
LettersView.m
#import "LettersView.h"
#import "config.h"
#implementation LettersView{
NSInteger _xOffset, _yOffset;
}
- (id)initWithFrame:(CGRect)frame
{
NSAssert(NO, #"Use initWithLetter:andSideLength instead");
return nil;
}
-(instancetype)initWithLetter:(NSString*)letter andSideLength:(float)sideLength
{
//the letter background
UIImage* img = [UIImage imageNamed:#"btn_letter#2x.png"];
//create a new object
self = [super initWithImage:img];
if (self != nil) {
//resize the letters
float scale = sideLength/img.size.width;
self.frame = CGRectMake(0,0,img.size.width*scale, img.size.height*scale);
UIButton *lblChar = [[UIButton alloc] initWithFrame:self.bounds];
lblChar.tintColor = [UIColor blackColor];
lblChar.backgroundColor = [UIColor clearColor];
[lblChar setTitle:letter forState:UIControlStateNormal];
[lblChar addTarget:self action:#selector(displaychar:)forControlEvents:UIControlEventTouchUpInside];
[self addSubview:lblChar];
self.isMatched = NO;
_letter = letter;
self.userInteractionEnabled = YES;
}
return self;
}
-(void)displayChar:(id)sender {
UIButton *lblChar = (UIButton *)sender;
NSLog(#" The button's title is %#.", lblChar.currentTitle);
_clickLetter = lblChar.currentTitle;
if (self.clickDelegate) {
[self.clickDelegate letterView:self addChar:lblChar.currentTitle];
}
NSLog(#"hu %#", _clickLetter);
}
PlacesView.h
// PlacesView.m
#import "PlacesView.h"
#import "config.h"
#implementation PlacesView
-(id)initWithFrame:(CGRect)frame {
NSAssert(NO, #"Use initwithletter");
return nil;
}
-(instancetype)initWithLetter:(NSString *)letter andSideLength:(float)sideLength
{
UIImage *img = [UIImage imageNamed:#"btn_input#2x.png"];
self = [super initWithImage: img];
if (self != nil) {
self.isMatched = NO;
float scale = sideLength/img.size.width;
self.frame = CGRectMake(0, 0, img.size.width*scale, img.size.height*scale);
//bullshit time
_fieldForLetter = [[UILabel alloc] initWithFrame:self.bounds];
_fieldForLetter.textAlignment = NSTextAlignmentCenter;
_fieldForLetter.textColor = [UIColor blackColor];
_fieldForLetter.backgroundColor = [UIColor clearColor];
_fieldForLetter.text = #"*"; // if button pressed button title placed here.
[self addSubview:_fieldForLetter];
_letter = letter;
}
return self;
}
#end
GameController.m
#import "GameController.h"
#import "config.h"
#import "LettersView.h"
#import "PlacesView.h"
#import "AppDelegate.h"
#implementation GameController {
//tile lists
NSMutableArray* _letters;
NSMutableArray* _places;
}
-(instancetype)init {
self = [super init];
if (self != nil) {
self.points = [[PointsController alloc] init];
self.audioController = [[AudioController alloc] init];
[self.audioController preloadAudioEffects: kAudioEffectFiles];
}
return self;
}
-(void)dealRandomWord {
NSAssert(self.level.words, #"Level not loaded");
// random word from plist
NSInteger randomIndex = arc4random()%[self.level.words count];
NSArray* anaPair = self.level.words[ randomIndex ];
NSString* word1 = anaPair[1]; // answer
NSString* word2 = anaPair[2]; // some letters
_helpstr = anaPair[3]; // helper
NSLog(#"qweqweq %# %#" , word1 , word2);
NSInteger word1len = [word1 length];
NSInteger word2len = [word2 length];
NSLog(#"phrase1[%li]: %#", (long)word1len, word1);
NSLog(#"phrase2[%li]: %#", (long)word2len, word2);
//calculate the letter size
float letterSide = ceilf( kScreenWidth*0.9 / (float)MAX(word1len, word2len) ) - kTileMargin;
//get the left margin for first letter
float xOffset = (kScreenWidth - MAX(word1len, word2len) * (letterSide + kTileMargin))/2;
//adjust for letter center
xOffset += letterSide/2;
float yOffset = 1.5* letterSide;
// init places list
_places = [NSMutableArray arrayWithCapacity: word1len];
// create places
for (NSInteger i = 0; i<word1len; i++){
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
PlacesView* place = [[PlacesView alloc] initWithLetter:letter andSideLength:letterSide];
place.center = CGPointMake(xOffset + i*(letterSide + kTileMargin), kScreenHeight/4);
[self.gameView addSubview:place];
[_places addObject: place];
}
}
//init letters list
_letters = [NSMutableArray arrayWithCapacity: word2len];
//create letter
for (NSInteger i=0;i<word2len;i++) {
NSString* letter = [word2 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
LettersView* letv = [[LettersView alloc] initWithLetter:letter andSideLength:letterSide];
letv.center = CGPointMake(xOffset + i * (letterSide + kTileMargin), kScreenHeight); // "/3*4"
if (i > 6) {
letv.center = CGPointMake(-5.15 * xOffset + i * (letterSide + kTileMargin), kScreenHeight + yOffset); // "/3*4"
}
letv.clickDelegate = self;
[self.gameView addSubview:letv];
[_letters addObject: letter];
}
}
}
-(void)letterView:(LettersView *)letterView addChar:(NSString *)addChar
{
PlacesView* placesView = nil;
for (PlacesView* pl in _places) {
//if (CGRectContainsPoint(pl.frame, pt)) {
if () {
//placesView = pl;
placesView.fieldForLetter.text = letterView.lblChar.currentTitle;
break;
}
}
//1 check if target was found
if (placesView!=nil) {
//2 check if letter matches
if ([placesView.letter isEqualToString: letterView.letter]) {
[self placeLetter:letterView atTarget:placesView];
[self.audioController playEffect: kSoundLetterTap];
self.points.points += self.level.coinsPerLvl; //ne nado tak
NSLog(#"Current points %d" , self.points.points);
[self checkForSuccess];
} else {
[self.audioController playEffect:kSoundFail];
[self addAlert:#"ne success" andMessage:#"You lose!" andButton:#"eshe cyka"];
}
}
}
-(void)placeLetter:(LettersView*)letterView atTarget:(PlacesView*)placeView {
placeView.isMatched = YES;
letterView.isMatched = YES;
letterView.userInteractionEnabled = NO;
}
-(void)checkForSuccess {
for (PlacesView* p in _places) {
//no success, bail out
if (p.isMatched==NO) return;
}
NSLog(#"ya!");
[self addAlert:#"Success" andMessage:#"You win!" andButton:#"eshe cyka"];
[self.audioController playEffect:kSoundSuccess];
}
-(void)addAlert: (NSString *)addTitle andMessage: (NSString *)alertMessage andButton: (NSString *)alertButton {
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow* window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.rootViewController = [UIViewController new];
window.windowLevel = UIWindowLevelAlert + 1;
UIAlertController *alert = [UIAlertController alertControllerWithTitle: addTitle message:alertMessage preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction= [UIAlertAction actionWithTitle:alertButton style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
window.hidden = YES;
}];
[alert addAction:defaultAction];
[window makeKeyAndVisible];
[window.rootViewController presentViewController:alert animated:YES completion:nil];
});
}
#end

Your GameController needs to keep a reference to PlacesView. It can also assign the action into LettersView so when the button in LettersView is pressed, the GameController will fetch it and perform an action in PlacesView. GameController is what both the other classes have in common, so it can handle any actions between them.
Another option is to use NSNotificationCenter and post a message in LettersView when the button is pressed, and listen for it in PlacesView.
Yet anther way is using a delegates where GameController makes sure that PlacesView is set as the delegate. When LettersView's button is pressed, it will call the delegate method which PlacesView listens to.
I'd go with first option.

Related

How to retrieve data properly using realm

I had a problem to retrieve data using realm. What i wanna do is caching the data so that i can use it when user first load the app or user does not have internet connection. Below is the logic what i wanna do.
request from fb api -> fb return 10 data -> display returned data and cache returned data -> if user doesn't have internet connection display cache data or if user have internet connection fetch new data.
below is my code :
FBVideo.h
#import <Realm/Realm.h>
#interface FBVideo : RLMObject
#property (nonatomic, strong) NSString *pageBefore;
#property (nonatomic, strong) NSString *pageAfter;
#property (nonatomic, strong) NSString *thumbnailsURI;
#property (nonatomic, strong) NSString *titleDescription;
#property NSString *id;
#end
FBVideo.m
#import "FBVideo.h"
#implementation FBVideo
+ (NSString *)primaryKey {
return #"id";
}
// Specify default values for properties
+ (NSDictionary *)defaultPropertyValues {
return #{#"pageBefore":#"", #"pageAfter":#"", #"thumbnailsURI":#"", #"titleDescription":#""};
}
+ (NSArray *)ignoredProperties {
return #[];
}
#end
PageVideosCVC.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "FBVideo.h"
#interface PageVideosCVC : UICollectionViewController
#property (strong, nonatomic) NSMutableArray *videoArray;
#property (strong, nonatomic) NSString *pageID;
#property (strong, nonatomic) NSString *pageName;
#property (strong, nonatomic) MPMoviePlayerController *playerController;
#property (assign, nonatomic) CATransform3D initialTransformation;
#property (nonatomic, strong) NSMutableSet *shownIndexes;
//#property (strong, nonatomic) FBVideo *fbVideoRealm;
#end
PageVideosCVC.m
#import "PageVideosCVC.h"
#import "facebook.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import <AFNetworking/AFNetworking.h>
#import <AVFoundation/AVFoundation.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <QuartzCore/QuartzCore.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 PageVideosCVC () <UICollectionViewDataSource,UICollectionViewDelegate> {
NSString *pageBefore;
NSString *pageAfter;
NSString *thumbnailsURI;
Reachability *internetReachable;
NSDictionary *videoInfoToSaveInRealm;
// RLMResults *videoResultsFrom
}
#end
#implementation PageVideosCVC
#synthesize videoArray;
static NSString * const reuseIdentifier = #"Cell";
- (void) viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
videoArray = [NSMutableArray array];
/* Make a card effect, rotate the angle of the collectionviewcell to -15
1) Start with an identity transform, which is a fancy math term for “do nothing.”
2) Call CATransform3DRotate to apply a rotation of -15 degrees (in radians), where the negative value indicates a clockwise rotation.
3) Apply the rotation around the axis 0.0, 0.0, 1.0; this represents the z-axis, where x=0, y=0, and z=1.
4) Applying just the rotation to the card isn’t enough, as this simply rotates the card about its center. To make it look like it’s tipped over on a corner, add a translation or shift where the negative values indicate a shift up and to the left.
*/
CGFloat rotationAngleDegrees = -15;
CGFloat rotationAngleRadians = rotationAngleDegrees * (M_PI/180);
CGPoint offsetPositioning = CGPointMake(-20, -20);
CATransform3D transform = CATransform3DIdentity;
transform = CATransform3DRotate(transform, rotationAngleRadians, 0.0, 0.0, 1.0);
transform = CATransform3DTranslate(transform, offsetPositioning.x, offsetPositioning.y, 0.0);
_initialTransformation = transform;
_shownIndexes = [NSMutableSet set];
}
- (void)viewWillAppear:(BOOL)animated {
UINavigationBar *navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
navBar.barTintColor = UIColorFromRGB(0x266593);
// Altering the font style of the navigation bar title
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
shadow.shadowOffset = CGSizeMake(0, 1);
[[UINavigationBar appearance] setTranslucent:NO];
[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
shadow, NSShadowAttributeName,
[UIFont fontWithName:#"HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
[self.view addSubview: navBar];
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"Down Arrow.png"] style:UIBarButtonItemStyleBordered target:self action:#selector(backButtonTapped:)];
// UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:#"Back"
// style:UIBarButtonItemStylePlain
// target:self
// action:#selector(backButtonTapped:)];
[cancelItem setTintColor:[UIColor whiteColor]];
// UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:#"Done"
// style:UIBarButtonItemStyleBordered
// target:self action:nil];
NSString *selectedPageName = [[NSString alloc] initWithFormat:#"%#", self.pageName];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:selectedPageName];
// navItem.rightBarButtonItem = doneItem;
navItem.leftBarButtonItem = cancelItem;
navBar.items = [NSArray arrayWithObjects: navItem,nil];
[UIBarButtonItem appearance].tintColor = [UIColor blueColor];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[self loadVideo:#"a" pagesID:self.pageID];
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if ([pageBefore isEqual:pageBefore]) {
return videoArray.count;
}
return videoArray.count + 1;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == [videoArray count] - 1) {
NSLog(#"page after : %#", pageAfter);
[self loadVideo:pageAfter pagesID:self.pageID];
}
if (![self.shownIndexes containsObject:indexPath]) {
[self.shownIndexes addObject:indexPath];
// Transform collectionviewcell layer
UIView *card = [(UICollectionViewCell*)cell contentView];
card.layer.transform = self.initialTransformation;
card.layer.opacity = 0.5;
[UIView animateWithDuration:0.5 animations:^{
card.layer.transform = CATransform3DIdentity;
card.layer.opacity = 1;
}];
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
__weak typeof(self) weakSelf = self;
if (indexPath.row == [videoArray count]) {
NSLog(#"this is last cell, later make it UIActivityIndicatorView");
} else {
// RLMResults *objects;
//
// objects = [FBVideo allObjects];
// FBVideo *fbVideoRealm = objects[indexPath.row];
//
// UIImageView *imgView = (UIImageView *)[cell viewWithTag:100];
// NSURL *thumbnailImage = [NSURL URLWithString:fbVideoRealm.thumbnailsURI];
// [imgView sd_setImageWithURL:thumbnailImage placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
//
// UILabel *titleDescription = (UILabel *)[cell viewWithTag:10];
// titleDescription.text = fbVideoRealm.titleDescription;
NSDictionary *videoData = weakSelf.videoArray[indexPath.row];
NSDictionary *videoThumbnails = [videoData valueForKey:#"thumbnails"];
NSArray *thumbnailsData = [videoThumbnails objectForKey:#"data"][0];
thumbnailsURI = [thumbnailsData valueForKey:#"uri"];
UIImageView *imgView = (UIImageView *)[cell viewWithTag:100];
NSURL *thumbnailImage = [NSURL URLWithString:thumbnailsURI];
[imgView sd_setImageWithURL:thumbnailImage placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
UILabel *titleDescription = (UILabel *)[cell viewWithTag:10];
titleDescription.text = videoData[#"description"];
}
return cell;
}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *videoSource = videoArray[indexPath.row];
NSURL *videoURL = [NSURL URLWithString:[videoSource valueForKey:#"source"]];
self.playerController = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
[[self.playerController view] setFrame:[self.view bounds]]; // Frame must match parent view
[self.view addSubview:[self.playerController view]];
self.playerController.movieSourceType = MPMovieSourceTypeStreaming;
self.playerController.controlStyle = MPMovieControlStyleFullscreen;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doneButtonClick:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self.playerController play];
// Play the video using AVPlayer iOS9 above
// AVPlayer *player = [AVPlayer playerWithURL:videoURL];
// AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
// playerLayer.frame = self.view.bounds;
// [self.view.layer addSublayer:playerLayer];
// [player play];
}
- (void)doneButtonClick:(NSNotification*)aNotification{
NSNumber *reason = [aNotification.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if ([reason intValue] == MPMovieFinishReasonUserExited) {
// Your done button action here
// [self dismissViewControllerAnimated:YES completion:nil];
NSLog(#"done button tapped");
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerDidExitFullscreenNotification
object:nil];
[self.playerController stop];
[self.playerController.view removeFromSuperview];
}
}
- (IBAction)backButtonTapped:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Helper Methods
- (void)loadVideo:(NSString*)currentPage pagesID:(NSString*)pagesID{
__weak typeof(self) weakSelf = self;
NSString *fbToken = [facebook currentFBAccessToken];
NSString *fbNextVideoURL = [NSString stringWithFormat:#"https://graph.facebook.com/v2.5/%#/videos?access_token=%#&pretty=0&fields=source,description,thumbnails.limit(1),length&limit=10&after=%#", pagesID, fbToken, currentPage];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:fbNextVideoURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *videoDict = [[NSDictionary alloc] initWithDictionary:responseObject];
if (responseObject != nil) {
[weakSelf.videoArray addObjectsFromArray:[videoDict valueForKeyPath:#"data"]];
pageBefore = [videoDict valueForKeyPath:#"paging.cursors.before"];
pageAfter = [videoDict valueForKeyPath:#"paging.cursors.after"];
// Caching pageBefore, pageAfter, thumbnailsURI, titleDescription data to REALM
for (videoInfoToSaveInRealm in weakSelf.videoArray) {
NSDictionary *videoThumbnails = [videoInfoToSaveInRealm valueForKey:#"thumbnails"];
NSArray *thumbnailsData = [videoThumbnails objectForKey:#"data"][0];
[[RLMRealm defaultRealm] transactionWithBlock:^{
[FBVideo createOrUpdateInDefaultRealmWithValue:#{#"id": self.pageID, #"titleDescription": videoInfoToSaveInRealm[#"description"], #"thumbnailsURI": [thumbnailsData valueForKey:#"uri"], #"pageBefore": pageBefore, #"pageAfter": pageAfter}];
}];
[self retrieveDataFromRealm];
}
//NSLog(#"first product's image: %#", (FBVideo *)[FBVideo allObjects]);
// Update UICollectionView UI
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self.collectionView reloadData];
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
- (void)retrieveDataFromRealm {
RLMResults *objects;
objects = [FBVideo allObjects];
FBVideo *fbVideoRealm = [[FBVideo alloc] init];
for (fbVideoRealm in objects) {
// NSLog(#"realm object count : %d", (int)objects.count);
NSLog(#"realm description : %#", fbVideoRealm.titleDescription);
NSLog(#"realm thumbnails URi : %#", fbVideoRealm.thumbnailsURI);
NSLog(#"realm page before : %#", fbVideoRealm.pageBefore);
NSLog(#"realm page after : %#", fbVideoRealm.pageAfter);
};
}
#end
Thank you in advance.
You should store the Facebook API response directly in Realm (don't display it right away), and then you can follow the pattern demonstrated in Realm's "TableView" example to back your UITableView with an RLMResults, and update the table when its data changes.
Since you'll always be loading data from the Realm this way, you get offline mode "for free".

UIViewController crashing after being called the 2nd time

This probably has a really simple fix, but I have a UITableViewController that calls a UIViewController in a normal list/detail configuration.
Since I added 2 subviews to the detail viewcontroller the app has been crashing on the second time I display the detail view controller.
I do lots of setup etc. when the view is loaded, but I have gone through and I can't find anything that has been set to null etc. None of the initialising functions crash the app. It's only once they are done that the app falls over. I assume the detail view controller is going through the same initialization each time...
Has anyone encountered this before?
Here is where the detail view controller is called:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
/***************************************************************************************
The detail view is just sent the tank object for the selected tank. The detail view
loads the labels and gauge with the appropriate information
***************************************************************************************/
self.detailViewController = [[tankDetailViewController alloc] init];
self.detailViewController = segue.destinationViewController;
[segue.destinationViewController setTankToShow:self.selectedTank];
}
and the following is the code for the detailviewcontroller:
#interface tankDetailViewController () <iTanksV2ListViewControllerDelegate>
//#property (nonatomic, strong) tankReleasedProductListTVCViewController* releasedProductList;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *tankGaugeHeightConstraint;
#property (weak, nonatomic) IBOutlet UIView *tankDetailView;
#property (weak, nonatomic) IBOutlet UIView *tankTrendView;
#property (nonatomic, strong) CPTGraphHostingView* hostView;
#property (strong, nonatomic) CPTGraph* graph;
#property BOOL isFirstValue;
#property double startValue;
#property double lastValue;
#end
#implementation tankDetailViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
/*************************************************************************************
All we need to do here, is to display all the information from the tank object in the
labels in the view.
The only thing of note is that we convert the volumes to doubles, and then use them to
calculate the percentFilled property of the tankGauge object.
************************************************************************************/
[super viewDidLoad];
self.isFirstValue = YES;
self.tankNumberLabel.text = [#"T" stringByAppendingString: self.tankToShow.tankNumber];
self.tankAvailableProductLabel.text = self.tankToShow.tankPumpableVolume;
self.tankProductLabel.text = self.tankToShow.tankProduct.name;
self.tankMaxVolumeLabel.text = self.tankToShow.tankMaxVolume;
self.tankGaugeHeightConstraint.constant = ([self.tankToShow.tankTotalVolume doubleValue]/[self.tankToShow.tankMaxVolume doubleValue]) * self.tankGaugeScaleView.frame.size.height;
self.tankTotalVolumeLabel.text = self.tankToShow.tankTotalVolume;
self.tankProductCode.text = self.tankToShow.tankProduct.code;
self.tankStatusLabel.text = self.tankToShow.tankStatus;
if([self.tankToShow.tankStatus isEqualToString:#"Process"])
{
[self.tankStatusLED setImage:[UIImage imageNamed:#"red_btn.png"] forState:UIControlStateNormal];
}
else if([self.tankToShow.tankStatus isEqualToString:#"Release"])
{
[self.tankStatusLED setImage:[UIImage imageNamed:#"green_btn.png"] forState:UIControlStateNormal];
}
else if([self.tankToShow.tankStatus isEqualToString:#"For Test"])
{
[self.tankStatusLED setImage:[UIImage imageNamed:#"amber_btn.png"] forState:UIControlStateNormal];
} else
{
[self.tankStatusLED setImage:[UIImage imageNamed:#"grey_btn.png"] forState:UIControlStateNormal];
}
[self.view bringSubviewToFront:self.tankDetailView];
self.graphData = [TrendData getTrendDataForTank];
[self initPlot];
}
- (void)viewWillAppear:(BOOL)animated
{
[self.view bringSubviewToFront:self.tankDetailView];
}
-(void) viewDidDisappear:(BOOL)animated
{
}
- (void) initPlot
{
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
- (void) configureHost
{
self.hostView = [(CPTGraphHostingView*) [CPTGraphHostingView alloc] initWithFrame:self.tankTrendView.bounds];
self.hostView.allowPinchScaling = NO;
[self.tankTrendView addSubview:self.hostView];
}
- (void) configureGraph
{
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
[self.graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
self.hostView.hostedGraph = self.graph;
self.graph.title = [#"Trend Graph for " stringByAppendingString:self.tankNumberLabel.text];
CPTMutableTextStyle* titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor blackColor];
titleStyle.fontName = #"Helvetica-Neue Light";
titleStyle.fontSize = 10.0f;
self.graph.titleTextStyle = titleStyle;
self.graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
self.graph.titleDisplacement = CGPointMake(0.0f, 20.0f);
[self.graph.plotAreaFrame setPaddingLeft:50.0f];
[self.graph.plotAreaFrame setPaddingBottom:90.0f];
CPTXYPlotSpace* plotSpace = (CPTXYPlotSpace*) self.graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
self.graph.defaultPlotSpace.delegate = self;
self.graph.delegate = self;
}
- (void) configurePlots
{
CPTGraph* graph = self.hostView.hostedGraph;
CPTXYPlotSpace* plotSpace = (CPTXYPlotSpace*) graph.defaultPlotSpace;
CPTScatterPlot* aaplPlot = [[CPTScatterPlot alloc] init];
aaplPlot.dataSource = self;
CPTColor *aaplColor = [CPTColor redColor];
aaplPlot.delegate = self;
aaplPlot.plotLineMarginForHitDetection = 10;
aaplPlot.plotSymbolMarginForHitDetection = 10;
[graph addPlot:aaplPlot toPlotSpace:plotSpace];
[plotSpace scaleToFitPlots: [NSArray arrayWithObjects:aaplPlot, nil]];
CPTMutablePlotRange* xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange* yRange = [plotSpace.yRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
plotSpace.yRange = yRange;
CPTMutableLineStyle* aapleLineStyle = [aaplPlot.dataLineStyle mutableCopy];
aapleLineStyle.lineWidth = 2.5;
aapleLineStyle.lineColor = aaplColor;
aaplPlot.dataLineStyle = aapleLineStyle;
}
- (void) configureAxes
{
NSDate* refDate = [NSDate dateWithTimeIntervalSince1970:0];
CPTGraph* graph = self.hostView.hostedGraph;
CPTXYAxisSet* axes = (id)graph.axisSet;
CPTXYPlotSpace* plotSpace = (CPTXYPlotSpace*) self.graph.defaultPlotSpace;
axes.xAxis.minorTicksPerInterval = 0;
NSValue* firstValue = [self.graphData objectAtIndex:0];
NSValue* lastValue = [self.graphData objectAtIndex:self.graphData.count -1];
CGPoint firstPoint = [firstValue CGPointValue];
CGPoint lastPoint = [lastValue CGPointValue];
axes.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromDouble(plotSpace.xRange.minLimitDouble);
axes.yAxis.majorIntervalLength = CPTDecimalFromDouble(plotSpace.yRange.lengthDouble/5);
axes.yAxis.minorTicksPerInterval = 0;
axes.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromDouble(plotSpace.yRange.minLimitDouble);
axes.xAxis.majorIntervalLength = CPTDecimalFromDouble((lastPoint.x - firstPoint.x)/3);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale currentLocale];
dateFormatter.dateFormat = #"dd/MM/yyyy HH:mm:ss";
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
timeFormatter.referenceDate = refDate;
axes.xAxis.labelFormatter = timeFormatter;
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if (fromInterfaceOrientation==UIInterfaceOrientationPortrait || fromInterfaceOrientation==UIInterfaceOrientationPortraitUpsideDown)
{
self.hostView.frame = self.view.bounds;
[self.graph reloadData];
[self.view bringSubviewToFront:self.tankTrendView];
}
else
{
self.hostView.frame = self.view.bounds;
[self.graph reloadData];
[self.view bringSubviewToFront:self.tankDetailView];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)didPressTankStatusLED:(UIButton *)sender {
//if([self.tankToShow.tankStatus isEqualToString:#"Release"])
//{
/*self.releasedProductList = [[tankReleasedProductListTVCViewController alloc] initWithStyle:UITableViewStylePlain];
Product* releasedProduct = [[Product alloc] init];
releasedProduct.name = self.tankProductLabel.text;
releasedProduct.code = self.tankProductCode.text;
self.releasedProductList.productList = [NSArray arrayWithObjects:releasedProduct, nil];
FPPopoverController* popoverController = [[FPPopoverController alloc]initWithViewController:self.releasedProductList];
self.releasedProductList.delegate = self;
popoverController.contentSize = CGSizeMake(250, 85 * self.releasedProductList.productList.count);
[popoverController presentPopoverFromView:self.tankStatusLED];*/
//}
}
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return self.graphData.count;
}
- (id)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
NSValue *value = [self.graphData objectAtIndex:idx];
CGPoint point = [value CGPointValue];
// FieldEnum determines if we return an X or Y value.
if ( fieldEnum == CPTScatterPlotFieldX )
{
return [NSNumber numberWithFloat:point.x];
}
else // Y-Axis
{
return [NSNumber numberWithFloat:point.y];
}
}
- (void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
}
//This function is here to lock the graph and prevent it from being panned so I can use the the drag event for my own purposes
-(CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)displacement {
return CGPointMake(0, 0);
}
- (BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(UIEvent *)event atPoint:(CGPoint)point
{
return NO;
}
- (BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(UIEvent *)event atPoint:(CGPoint)point
{
CPTGraph* graph = self.hostView.hostedGraph;
CPTXYAxisSet* axes = (id)graph.axisSet;
double percentAcrossScreen = point.x/self.view.frame.size.width;
if (self.isFirstValue==YES)
{
self.startValue = percentAcrossScreen;
self.isFirstValue = NO;
}
else
{
self.lastValue = percentAcrossScreen;
}
NSValue *firstValue = [self.graphData objectAtIndex:[[NSNumber numberWithDouble:self.startValue * self.graphData.count] integerValue]];
CGPoint firstPoint = [firstValue CGPointValue];
NSValue *lastValue = [self.graphData objectAtIndex:[[NSNumber numberWithDouble:self.lastValue * self.graphData.count] integerValue]];
CGPoint lastPoint = [lastValue CGPointValue];
double difference = lastPoint.x - firstPoint.x;
CPTPlotRange *range = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(firstPoint.x)
length:CPTDecimalFromDouble(difference)];
CPTFill *bandFill = [CPTFill fillWithColor:[CPTColor blueColor]];
[axes.yAxis addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:range
fill:bandFill]];
NSLog([[NSNumber numberWithDouble:firstPoint.x] stringValue]);
NSLog([[NSNumber numberWithDouble:lastPoint.x] stringValue]);
return YES;
}

No visible #interface for method declares the selector

I'm trying to write an app that takes photo from contact named Jan Kowalski and shows on screen.
I'm pretty new to iOS and xCode and so I got errors in my code.
Here's my .m file
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
//#synthesize labelNewImage;
#synthesize labelOldImage;
//#synthesize imageViewNew;
#synthesize imageViewOld;
- (void) changePositionOfView:(UIView *)paramView to:(CGFloat)paramY
{
CGRect viewFrame = paramView.frame;
viewFrame.origin.y = paramY;
paramView.frame = viewFrame;
}
- (void) createLabelAndImageViewForOldImage
{
self.labelOldImage = [[UILabel alloc] initWithFrame:CGRectZero];
self.labelOldImage.text = #"Obraz";
self.labelOldImage.font = [UIFont systemFontOfSize:16.0f];
[self.labelOldImage sizeToFit];
self.labelOldImage.center = self.view.center;
[self.view addSubview:self.labelOldImage];
[self changeYPositionOfView:[self.labelOldImage
to:80.0f]];// error - no visible #interface for 'UILabel' that declares the selector to
self.imageViewOld = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
self.imageViewOld.center = self.view.center;
self.imageViewOld.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:self.imageViewOld];
[self changeYPositionOfView:[self.imageViewOld to:105.0f]];
}
- (ABRecordRef)getPersonWithFirstName:(NSString *)paramFirstName
lastName:(NSString *)paramLastName
inAddressBook:(ABRecordRef)paramAddressBook
{
ABRecordRef result = NULL;
if (paramAddressBook == NULL) {
NSLog(#"Ksiazka ma wartosc NULL");
return NULL;
}
NSArray *allPeople = (__bridge_transfer NSArray *)
ABAddressBookCopyArrayOfAllPeople(paramAddressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter=0; peopleCounter < [allPeople count]; peopleCounter++) {
ABRecordRef person = (__bridge ABRecordRef)
[allPeople objectAtIndex:peopleCounter];
NSString *firstName = (__bridge_transfer NSString *)
ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)
ABRecordCopyValue(person, kABPersonLastNameProperty);
BOOL firstNameIsEqual = NO;
BOOL lastNameIsEqual = NO;
if ([firstName length] == 0 && [paramFirstName length] == 0)
{
firstNameIsEqual = YES;
}
else if ([firstName isEqualToString:paramFirstName])
{
firstNameIsEqual = YES;
}
if ([lastName length] == 0 && [paramLastName length] == 0)
{
lastNameIsEqual = YES;
}
else if ([lastName isEqualToString:paramLastName])
{
lastNameIsEqual = YES;
}
if (firstNameIsEqual && lastNameIsEqual) {
return person;
}
}
return result;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blackColor];
[self createLabelAndImageViewForOldImage];
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook !=NULL) {
ABRecordRef janKowalski = [self getPersonWithFirstName:#"Jan" lastName:#"Kowalski" inAddressBook:addressBook];
if (janKowalski == NULL) {
NSLog(#"Nie znaleziono kontaktu tworzenie nowego.");
janKowalski = [self newPersonWithFirstName:#"Jan" // error - no visible #interface for 'ViewController' that declares the selector 'newPersonWithFirstName
lastName:#"Kowalski"
inAddressBook:addressBook];
}
if (janKowalski == NULL) {
NSLog(#"Nie udało się utworzyć nowego rekordu dla tego kontaktu.");
CFRelease(addressBook);
return;
}
self.imageViewOld.image = [[self getPersonImage]:janKowalski]; // error - no visible #interface for 'ViewController' delcares the selector 'getPersonImage'
}
}
and my .h file:
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) UILabel *labelOldImage;
#property (strong, nonatomic) UIImageView *imageViewOld;
#end
I'm getting these "no visible #interface for 'UILabel' that declares the selector to" errors.
Could you guys get me on the right way how to solve this problem?
Thank you so much!
It's really just an error in placing square brackets. You've defined a method with two parameters...
changePositionOfView:(UIView *)paramView to:(CGFloat)paramY
...but you're calling it with only one...
[self changeYPositionOfView:[self.labelOldImage to:80.0f]];
Check the matching of the brackets.
The compiler thinks you want to call [self.labelOldImage to:80.0f] and pass the result to a single-parameter method called justchangeYPositionOfView:.
Pass values to both parameters by fixing the nesting:
[self changeYPositionOfView:self.labelOldImage to:80.0f];
The problem:
- changePositionOfView:(UIView *)paramView to:(CGFloat)paramY
But you send this:
[self changeYPositionOfView:[self.labelOldImage
to:80.0f]];// error - no visible #interface for 'UILabel' that declares the selector to
Make it with 2 params.
And yeah, when you use #synthesize, after that call label/image with labelOldImager, not self.labelOldImage.

custom UIProgressView class works on 64 bit device but not others

I have a custom UIProgressView class (from John Rommel Estropia) which works perfect on 64 bit iPhone simulator and device. But when I run it on 32bit simulators/devices it did not show on the screen? Any idea?
This problem also valid for another class for drawing circular progress.
Here is .m file:
#import "SPKProgress.h"
#interface SPKProgress()
#property (nonatomic, weak) UIImageView *trackImageView;
#property (nonatomic, weak) UIImageView *progressImageView;
#end
#implementation SPKProgress
#pragma mark - NSObject
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self setupProgressView];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self setupProgressView];
}
return self;
}
#pragma mark - UIView
- (void)layoutSubviews
{
[super layoutSubviews];
UIImageView *trackImageView = self.trackImageView;
UIImageView *progressImageView = self.progressImageView;
if (!trackImageView || !progressImageView)
{
return;
}
CGRect bounds = self.bounds;
CGFloat boundsTop = CGRectGetMinY(bounds);
UIImage *trackImage = self.trackImage;
if (trackImage)
{
CGRect trackFrame = trackImageView.frame;
CGFloat trackHeight = trackImage.size.height;
trackImageView.frame = (CGRect){
.origin.x = CGRectGetMinX(trackFrame),
.origin.y = (boundsTop
+ ((CGRectGetHeight(bounds) - trackHeight) * 0.5f)),
.size.width = CGRectGetWidth(trackFrame),
.size.height = trackHeight
};
}
UIImage *progressImage = self.progressImage;
if (progressImage)
{
CGRect progressFrame = progressImageView.frame;
CGFloat progressHeight = progressImage.size.height;
progressImageView.frame = (CGRect){
.origin.x = CGRectGetMinX(progressFrame),
.origin.y = (boundsTop
+ ((CGRectGetHeight(bounds) - progressHeight) * 0.5f)),
.size.width = CGRectGetWidth(progressFrame),
.size.height = progressHeight
};
}
}
#pragma mark - UIProgressView
- (void)setProgressImage:(UIImage *)progressImage
{
[super setProgressImage:progressImage];
self.progressImageView.image = progressImage;
}
- (void)setTrackImage:(UIImage *)trackImage
{
[super setTrackImage:trackImage];
self.trackImageView.image = trackImage;
}
#pragma mark - private
- (void)setupProgressView
{
if ([self compareVersionString:[UIDevice currentDevice].systemVersion
withVersionString:#"7.1"] == NSOrderedAscending)
{
return;
}
NSArray *subviews = self.subviews;
if ([subviews count] != 2)
{
return;
}
for (UIView *subview in subviews)
{
if (![subview isKindOfClass:[UIImageView class]])
{
return;
}
}
self.trackImageView = subviews[0];
self.progressImageView = subviews[1];
self.trackImageView.image = self.trackImage;
self.progressImageView.image = self.progressImage;
}
- (NSComparisonResult)compareVersionString:(NSString *)versionString1
withVersionString:(NSString *)versionString2
{
NSArray *components1 = [versionString1 componentsSeparatedByString:#"."];
NSArray *components2 = [versionString2 componentsSeparatedByString:#"."];
NSUInteger components1Count = [components1 count];
NSUInteger components2Count = [components2 count];
NSUInteger partCount = MAX(components1Count, components2Count);
for (NSInteger part = 0; part < partCount; ++part)
{
if (part >= components1Count)
{
return NSOrderedAscending;
}
if (part >= components2Count)
{
return NSOrderedDescending;
}
NSString *part1String = components1[part];
NSString *part2String = components2[part];
NSInteger part1 = [part1String integerValue];
NSInteger part2 = [part2String integerValue];
if (part1 > part2)
{
return NSOrderedDescending;
}
if (part1 < part2)
{
return NSOrderedAscending;
}
}
return NSOrderedSame;
}
#end
And the header file:
#import <UIKit/UIKit.h>
#interface SPKProgress : UIProgressView
#end

Xcode button linking error?

Hey I was wondering is their any possible way I can link two actions to the same button in Xcode? I've already tried but keep getting this error: "terminating with uncaught exception of type NSException". So i'm guessing I am not able to do that? See what i'm trying to do is
make a button play a sound but that same button is also linked to starting a new round in the game. How would I go about doing this? I've currently got this going in my .m file.
#import "BullsEyeViewController.h"
#interface BullsEyeViewController ()
#end
#implementation BullsEyeViewController
{
int _currentValue;
int _targetValue;
int _score;
int _round;
}
- (IBAction)playSound:(id)sender {
SystemSoundID soundID;
NSString *buttonName=[sender currentTitle];
NSString *soundFile=[[NSBundle mainBundle]
pathForResource:buttonName ofType:#"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)
[NSURL fileURLWithPath:soundFile], &
soundID);
AudioServicesPlaySystemSound(soundID);
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self startNewGame];
[self updateLabels];
UIImage *thumbImageNormal = [UIImage
imageNamed:#"SliderThumb-Normal"];
[self.slider setThumbImage:thumbImageNormal
forState:UIControlStateNormal];
UIImage *thumbImageHighlighted = [UIImage
imageNamed:#"SliderThumb-Highlighted"];
[self.slider setThumbImage:thumbImageHighlighted
forState:UIControlStateHighlighted];
UIImage *trackLeftImage =
[[UIImage imageNamed:#"SliderTrackLeft"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 14, 0, 14)];
[self.slider setMinimumTrackImage:trackLeftImage
forState:UIControlStateNormal];
UIImage *trackRightImage =
[[UIImage imageNamed:#"SliderTrackRight"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 14, 0, 14)];
[self.slider setMaximumTrackImage:trackRightImage
forState:UIControlStateNormal];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)startNewRound
{
_round += 1;
_targetValue = 1 + arc4random_uniform(100);
_currentValue = 50;
self.slider.value = _currentValue;
}
- (void)startNewGame
{
_score = 0;
_round = 0;
[self startNewRound];
}
- (void)updateLabels
{
self.targetLabel.text = [NSString stringWithFormat:#"%d",
_targetValue];
self.scoreLabel.text = [NSString stringWithFormat:#"%d",
_score];
self.roundLabel.text = [NSString stringWithFormat:#"%d",
_round];
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)showAlert
{
int difference = abs(_targetValue - _currentValue);
int points = 100 - difference;
NSString *title;
if (difference == 0) {
title = #"Perfect!";
points += 100;
} else if (difference < 5) {
title = #"You almost had it!";
if (difference == 1) {
points += 50;
}
} else if (difference < 10 ) {
title = #"Pretty good!";
} else {
title = #"Not even close...";
}
_score+=points;
NSString *message = [NSString stringWithFormat:#"You scored %d points", points];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
}
-(IBAction)sliderMoved:(UISlider *)slider
{
_currentValue = lroundf(slider.value);
}
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self startNewRound];
[self updateLabels];
}
-(IBAction)startOver
{
CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;
transition.duration = 1;
transition.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionEaseOut];
[self startNewGame];
[self updateLabels];
[self.view.layer addAnimation:transition forKey:nil];
}
#end
And here's my .h file.
//
// BullsEyeViewController.h
// BullsEye
//
// Created by Sebastian Shelley on 28/04/2014.
// Copyright (c) 2014 Sebastian Shelley. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#interface BullsEyeViewController : UIViewController
<UIAlertViewDelegate>
#property (nonatomic, weak) IBOutlet UISlider *slider;
#property (nonatomic, weak) IBOutlet UILabel *targetLabel;
#property (nonatomic, weak) IBOutlet UILabel *scoreLabel;
#property (nonatomic, weak) IBOutlet UILabel *roundLabel;
-(IBAction)showAlert;
-(IBAction)sliderMoved:(UISlider *)slider;
-(IBAction)startOver;
- (IBAction)playSound:(id)sender;
#end
Some help would be greatly appreciated :)
Add an action like this to the button
-(IBAction)myButtonPressed:(id)sender
{
[self playSound:sender];
[self startNewRound:Sender];
}
Use only one action, just set a BOOL to check if you need to play the sound or not.
Example code would be:
-(IBAiction)btnPressed:(id)sender
{
if(playsound)
{
[self playSound];
playsound = NO;
}
[self startOver];
}
And then whenever you want the saund to be played again just set playsound to YES and next time user presses the button it will play the sound again

Resources