iPhone 遊戲中既播放背景音樂又播放特效聲音的辦法
有時候在 iPhone 遊戲中,既要播放背景音樂,同時又要播放比如槍的開火音效。此時您可以試試以下方法
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:fileNameofType:@"wav"]; //建立音樂檔案路徑
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
AVAudioPlayer* musicPlayer = [[AVAudioPlayer
alloc]
initWithContentsOfURL:musicURL error:nil];
[musicURL release];
[musicPlayer prepareToPlay];
//[musicPlayer setVolume:1]; //設定音量大小
//musicPlayer .numberOfLoops = -1;//設定音樂播放次數 -1 為一直循環
要 導 入 框 架 AVFoundation.framework , 頭 文 件 中<AVFoundation/AVFoundation.h>;做成類的話則更友善。
NSNotificationCenter 用于增加回調函數
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(_willBecomeActive) name:UIApplicationDidBecomeActiveNotificationobject:nil];
UINavigationBar 背景 HackLOGO_320×44.png 圖檔顯示在背景上,
更多蘋果移動應用開發入門精選文檔教程荟萃:http://down.51cto.com/zt/2401
@implementation UINavigationBar (UINavigationBarCategory)- (void)drawRect:(CGRect)rect {
//加入旋轉坐标系代碼// Drawing code
UIImage *navBarImage = [UIImage imageNamed:@"LOGO_320×44.png"];CGContextRef context = UIGraphicsGetCurrentContext();CGContextTranslateCTM(context, 0.0, self.frame.size.height);CGContextScaleCTM(context, 1.0, -1.0);
CGPoint center=self.center;
CGImageRef cgImage= CGImageCreateWithImageInRect(navBarImage.CGImage,CGRectMake(0, 0, 1, 44));
CGContextDrawImage(context, CGRectMake(center.x-160-80, 0, 80, self.frame.size.height),cgImage);
CGContextDrawImage(context, CGRectMake(center.x-160, 0, 320, self.frame.size.height),navBarImage.CGImage);
CGContextDrawImage(context, CGRectMake(center.x+160, 0, 80, self.frame.size.height),cgImage);
}@end
old code
CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height),navBarImage.CGImage);
清除電話号碼中的其他符号(源碼)
最近從通訊錄讀取電話号碼,讀出得号碼如:134-1814-****。而我需要的為 11 位純數字,一直找方法解決此問題,今天終于找到了。
分享一下„„
代碼如下:
NSString *originalString = @"(123) 123123 abc";NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:@"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];}
// --------- Add the following to get out of endless loopelse {
[scanner setScanLocation:([scanner scanLocation] + 1)];}
// --------- End of addition}
NSLog(@"%@", strippedString); // "123123123"
正則判斷:字元串隻包含字母和數字
NSString *mystring = @"Letter1234";NSString *regex = @"[a-z][A-Z][0-9]";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([predicate evaluateWithObject:mystring] == YES) {//implement
}
修改 UITableview 滾動條顔色的方法
UITableview 的滾動條預設顔色是黑色的,如果 UItableview 背景也是深顔色,則
滾動條會變的很不明顯。您可以用下面這行代碼來改變滾動條的顔色
self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite;當然,最後的 “White” 也可以換成其它顔色。
一:确認網絡環境 3G/WIFI
1. 添加源檔案和 framework
%@",[m_request.responseHeaders
開發 Web 等網絡應用程式的時候,需要确認網絡環境,連接配接情況等資訊。如果沒有處理它們,是不會通過 Apple 的審(我們的)查的。
更多蘋果移動應用開發入門精選文檔教程荟萃:http://down.51cto.com/zt/2401
Apple 的 例程 Reachability 中介紹了取得/檢測網絡狀态的方法。要在應用程式程式中使用 Reachability,首先要完成如下兩部:
1.1. 添加源檔案:
在你的程式中使用 Reachability 隻須将該例程中的 Reachability.h 和Reachability.m 拷貝到你的工程中。如下圖:
1.2.添加 framework:
将 SystemConfiguration.framework 添加進工程。如下圖:
2. 網絡狀态
Reachability.h 中定義了三種網絡狀态:typedef enum {
NotReachable = 0,ReachableViaWiFi,ReachableViaWWAN
} NetworkStatus;
是以可以這樣檢查網絡狀态:
//無連接配接
//使用 3G/GPRS 網絡
//使用 WiFi 網絡
Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”];switch ([r currentReachabilityStatus]) {
}
case NotReachable:
// 沒有網絡連接配接
break;
case ReachableViaWWAN:
// 使用 3G 網絡
break;
case ReachableViaWiFi:
// 使用 WiFi 網絡break;
3.檢查目前網絡環境程式啟動時,如果想檢測可用的網絡環境,可以像這樣// 是否 wifi
+ (BOOL) IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] !=
更多蘋果移動應用開發入門精選文檔教程荟萃:http://down.51cto.com/zt/2401
NotReachable);}
// 是否 3G
+ (BOOL) IsEnable3G {
return ([[ReachabilitycurrentReachabilityStatus] != NotReachable);
}
例子:
- (void)viewWillAppear:(BOOL)animated {
reachabilityForInternetConnection]
if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus ==NotReachable) &&
NotReachable)) {
([Reachability reachabilityForLocalWiFi].currentReachabilityStatus ==
self.navigationItem.hidesBackButton = YES;
[self.navigationItem setLeftBarButtonItem:nil animated:NO];}
}
4. 連結狀态的實時通知
網絡連接配接狀态的實時檢查,通知在網絡應用中也是十分必要的。接續狀态發生變化時,需要及時地通知使用者:
Reachability 1.5 版本
// My.AppDelegate.h#import "Reachability.h"
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {NetworkStatus remoteHostStatus;
}
@property NetworkStatus remoteHostStatus;
@end
// My.AppDelegate.m#import "MyAppDelegate.h"
@implementation [email protected] remoteHostStatus;
// 更新網絡狀态
- (void)updateStatus {
self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
}
// 通知網絡狀态
- (void)reachabilityChanged:(NSNotification *)note {
[self updateStatus];
if (self.remoteHostStatus == NotReachable) {
UIAlertView *alert =initWithTitle:NSLocalizedString(@"AppName", nil)
[[UIAlertView
alloc]
[alert show];
[alert release];}
}
message:NSLocalizedString (@"NotReachable", nil)delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
// 程式啟動器,啟動網絡監視
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// 設定網絡檢測的站點
[[Reachability sharedReachability] setHostName:@"www.apple.com"];[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
// 設定網絡狀态變化時的通知函數
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:@"kNetworkReachabilityChangedNotification" object:nil];[self updateStatus];
}
- (void)dealloc {
// 删除通知對象
[[NSNotificationCenter defaultCenter] removeObserver:self];[window release];
[super dealloc];
}
Reachability 2.0 版本
// MyAppDelegate.h
@class Reachability;
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {Reachability *hostReach;
}@end
// MyAppDelegate.m
- (void)reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];NSParameterAssert([curReach isKindOfClass: [Reachability class]]);NetworkStatus status = [curReach currentReachabilityStatus];
if (status == NotReachable) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName""
}}
message:@"NotReachable"
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];[alert show];
[alert release];
- (void)applicationDidFinishLaunching:(UIApplication *)application {// ...
/ 監測網絡情況
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)name: kReachabilityChangedNotificationobject: nil];
hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"]
retain];
hostReach startNotifer];
// ...}
二:使用 NSConnection 下載下傳資料
1.建立 NSConnection 對象,設定委托對象
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURL URLWithString:[self urlString]]];
[NSURLConnection connectionWithRequest:request delegate:self];
2. NSURLConnection delegate 委托方法
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError
*)error;
三:使用 NSXMLParser 解析 xml 檔案
1. 設定委托對象,開始解析
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //或者也可以使用 initWithContentsOfURL 直接下載下傳檔案,但是有一個原因不這麼做:
// It's also possible to have NSXMLParser download the data, by passing it a URL, butthis is not desirable
// because it gives less control over the network, particularly in responding toconnection errors.
[parser setDelegate:self];[parser parse];
2. 常用的委托方法
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qNameattributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementNamenamespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName;
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml";
3. 應用舉例
- (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error{
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];[parser parse];
NSError *parseError = [parser parserError];
if (parseError && error) {
*error = parseError;}
[parser release];}
Iphone 實作畫折線圖
iphone 裡面要畫圖一般都是通過 CoreGraphics.framwork 和 QuartzCore.framwork 實作,apple的官方 sdk demon 中包含了 QuartzCore 的基本用法,
具體 demo 請參考 http://developer.apple.com/library/ios/#samplecode/QuartzDemo/
要實作折線圖也就把全部的點連起來,movePointLineto,具體的調用裡面的 api 就可以實作了,但是畫坐标就比較麻煩了,裡面需要去轉很多,好在國外有人開源了一個畫折線圖的開發包,首先看看效果吧,具體怎麼用可以參考作者 git 版本庫中的 wiki。http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library
這個包還提供了其他的很好看的 UI,都可以調來用,但是我們隻需要一個畫圖要把整個包都導進去,工程太大了,既然是開源的那就想辦法提取出來吧,原先之前也有人幹過這樣的事。http://duivesteyn.net/2010/03/07/iphone-sdk-implementing-the-tapku-graph-in-your-application/
在 UIImageView 中旋轉圖像
float rotateAngle = M_PI;
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);imageView.transform = transform;
以上代碼旋轉 imageView, 角度為 rotateAngle, 方向可以自己測試哦!