iOS开发_代码及解决方案收集
1、设置圆角view(只要是UIView的子类应该都可以)
将一个view得外部整成圆角
首先要引用导入QuartzCore.framework这个框架.
并且头部 #import <QuartzCore/QuartzCore.h>
关键代码如下:
m_view2.layer.cornerRadius = 10; // 设置边框的圆弧度
m_view2.layer.masksToBounds = YES; // without this, won't be round corner
m_view2.layer.borderWidth = 15; // 设置这个圆形边框的宽度,这句可以不用,可以试试,挺好玩的。
2、把图片切成圆角代码
(from:http://www.cocoachina.com/bbs/read.php?tid=1757&page=1)
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,
float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM(context, ovalWidth, ovalHeight);
fw = CGRectGetWidth(rect) / ovalWidth;
fh = CGRectGetHeight(rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2); // Start at lower right corner
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // Top right corner
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right
CGContextClosePath(context);
CGContextRestoreGState(context);
}
+ (id) createRoundedRectImage:(UIImage*)image size:(CGSize)size
{
// the size of CGContextRef
int w = size.width;
int h = size.height;
UIImage *img = image;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGRect rect = CGRectMake(0, 0, w, h);
CGContextBeginPath(context);
addRoundedRectToPath(context, rect, 10, 10);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}
直接调用createRoundedRectImage....
返回圆角图片
圆角大小自行修改CGContextAddArcToPoint….
3、在iPhone运行起来后,可以直接设置好手机的短消息中心,APN设置,与彩信相关设置
(from:http://www.cocoachina.com/bbs/read.php?tid=53920&keyword=%B6%CC%D0%C5)
http://support.apple.com/kb/HT4839
使用iphone设置工具,生成设置配置文件,然后安装到iphone上,比手动输入快,可以批量做。
4、iPhone的特殊URL:可打电话、发短信、发邮件。
http://www.cocoachina.com/iphonedev/sdk/2009/0611/242.html
在iPhone中,可以直接用UIApp打开URL地址。如下所示:
[ UIApp openURL: [ NSURL URLWithString:@"http://www.apple.com" ] ];
或者:
[ UIApp openURL: [ NSURL URLWithString:@"mailto:
[email protected]?Subject=hello" ] ];
与此同时,iPhone还包含一些其他除了http://或者mailto:之外的URL:
sms:// 可以调用短信程序
tel:// 可以拨打电话
(
tel:// 这个是打完后回不到app的。
telprompt:// 这个可以回到app,但是打电话前会多弹出一个alert,点了呼叫才会拨电话。
)
itms:// 可以打开MobileStore.app
audio-player-event:// 可以打开iPod
audio-player-event://?uicmd=show-purchased-playlist 可以打开iPod播放列表
video-player-event:// 可以打开iPod中的视频
https:// 可以打開基於https加密協議的URL。。。
如:拨打电话号码,[[UIApplication sharedApplication] openURL: [ NSURL URLWithString:@"tel://13437138025" ] ];
ps:模拟器不支持打电话、发短信和app store。
5、打电话结束后返回自己的应用
(from:http://www.cocoachina.com/bbs/read.php?tid=83937&page=e&#a (4楼) )
打电话可以用openURL:这个API, 如:[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];但是当电话结束后,返回的是系统的拨打电话界面,如何才能返回自己的应用呢?这儿有两种方法与大家分享。
第一种是用UIWebView加载电话,这种是合法的,可以上App Store的。
代码如下:
// assuming you have an ivar to store a weak reference to a UIWebView:
// UIWebView *phoneCallWebView;
- (void) dialPhoneNumber:(NSString *)aPhoneNumber
{
NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",aPhoneNumber]];
if ( !phoneCallWebView ) {
phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
}
[phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
}
- (void) dealloc
{
// cleanup
[phoneCallWebView release], phoneCallWebView = nil;
[super dealloc];
}
第二种是私有方法,不能上App Store的。(注:可以上App Store)
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://10086"]];
6、view的,渐变效果。(由透明->不透明->透明)
详见Demo:“Show&HideView"
- (void)showView
{
self.labelString.hidden = NO;
NSString* str = @"渐现中...";
self.labelString.frame = CGRectMake(100, 100, 100, 100);
self.labelString.text = str;
// alpha从0到1
self.labelString.alpha = 0;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kWaitingTime];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(hiddenWaitingView)];
self.labelString.alpha = 1;
[UIView commitAnimations];
}
- (void)hiddenWaitingView
{
// alpha从1到0
self.labelString.text = @"渐隐中...";
self.labelString.alpha = 1;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kWaitingTime];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(hiddenView)];
self.labelString.alpha = 0;
[UIView commitAnimations];
}
- (void)hiddenView
{
self.labelString.hidden=YES;
}
7、查看一些硬件信息
[[UIDevice currentDevice] name] // e.g. "My iPhone"
[[UIDevice currentDevice] model] // e.g. @"iPhone", @"iPod Touch"
[[UIDevice currentDevice] localizedModel] // localized version of model
[[UIDevice currentDevice] systemName] // e.g. @"iPhone OS"
[[UIDevice currentDevice] systemVersion] // e.g. @"2.0"
[[UIDevice currentDevice] uniqueIdentifier] // a string unique to each device based on various hardware info.
from:http://www.devdiv.com/forum.php?mod=viewthread&tid=122890&page=1#pid710813
#import <sys/utsname.h>
/*
* 获取版本型号
* "i386" simulator
* "iPod1,1" iPod Touch
* "iPhone1,1" iPhone
* "iPhone1,2" iPhone 3G
* "iPhone2,1" iPhone 3GS
* "iPad1,1" iPad
* "iPhone3,1" iPhone 4
* "iPhone4,1" iPhone 4
* "iPhone5,2" iPhone 4
*/
+ (NSString*)deviceString
{
// 需要#import "sys/utsname.h"
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
if ([deviceString isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([deviceString isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([deviceString isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([deviceString isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([deviceString isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
if ([deviceString isEqualToString:@"iPhone3,2"]) return @"Verizon iPhone 4";
if ([deviceString isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([deviceString isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([deviceString isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([deviceString isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([deviceString isEqualToString:@"iPad1,1"]) return @"iPad";
if ([deviceString isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([deviceString isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([deviceString isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([deviceString isEqualToString:@"i386"]) return @"Simulator";
if ([deviceString isEqualToString:@"x86_64"]) return @"Simulator";
NSLog(@"NOTE: Unknown device type: %@", deviceString);
return deviceString;
}
8、
Couldn't register com.mycompany.MyApp with the bootstrap server. Error: unknown error code.
This generally means that another instance of this process was already running or is hung in the debugger.
a. 重新Xcode
b. 重启device
c. clean
d. rebuild
if it is still errro, try to change the identifier name of ur app, it works for me.
9、定义任意的singleton对象(单例模式)
//可以在项目中 定义任意的singleton对象
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [[self alloc] init]; \
} \
} \
\
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return NSUIntegerMax; \
} \
\
- (oneway void)release \
{ \
} \
\
- (id)autorelease \
{ \
return self; \
}
10、重载release出现警告
- (void) release {}
会弹出警告
warning: Semantic Issue: Conflicting distributed object modifiers on return type in implementation of 'release'
查看NSObject的release方法,可以看到release的如下定义:
- (oneway void)release NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
在文档中查找oneway可以找到如下说明:
If the method is oneway, the sender of the remote message doesn’t block awaiting a reply.
在网上也可以找到如下说法:
release方法是不能回滚的。oneway单行线。
这一般是线程之间通信的接口定义。表示单向的调用
参考:http://www.cocoachina.com/bbs/read.php?tid=22676&keyword=oneway|void
11、自定义圆角渐变色样式带阴影效果的CellView
http://www.cocoachina.com/bbs/read.php?tid=25760&page=1
RoundShadowGradientCellView.zip(已下载)
12、显示和隐藏状态栏动画
-(void)hiddenBottomTabs:(BOOL)hidden animated:(BOOL)animated
{
if (animated==YES) {
//m_tabBar.userInteractionEnabled=NO;
NSString *dirString = @"";
if (hidden) {
dirString = kCATransitionFromBottom;
} else {
dirString = kCATransitionFromTop;
}
//通过动画控制视图的显示或隐藏
CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:kCATransitionPush];
[animation setSubtype:dirString];
[animation setDuration:0.5f];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
m_tabBar.hidden=hidden;
[m_tabBar.layer addAnimation:animation forKey:@"transitionViewAnimation"];
}else {
m_tabBar.hidden=hidden;
//m_tabBar.userInteractionEnabled=YES;
}
}
13、给ios模拟器加图片
直接把图片拖到模拟器里 或 用模拟器上网站,然后选个自己喜欢的图片,然后长按鼠标左键,保存
14、判断平台版本
用宏是在编译时确定平台版本。
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 50000
NSLog(@"ios5");
#else
NSLog(@"ios4");
#endif
在运行时选择平台
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) {
// iOS 5 code
}
else {
// iOS 4.x code
}
15、xcode 代码中大部分文字都是白色
Q:除了一些保留的关键字外 都是白色显示,如何改回来了
A:organizer->project->derived data 点右边的delete按钮
16 宏定义,判断是否高清屏 ,ipad,simulator
宏定义,判断是否高清屏 ,ipad,simulator ,方法如下:
// 是否高清屏
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ?
CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
// 是否iPad
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// 是否模拟器
#define isSimulator (NSNotFound != [[[UIDevice currentDevice] model] rangeOfString:@"Simulator"].location)
ps: TARGET_IPHONE_SIMULATOR 可以判断 target 是否是模拟器
17 自定义 UIAlertView
主要是在 初始化 UIAlertView 的 Title 时候加上换行符,换行符空白部分用来放置自定义的内容
UIAlertView * alertView=[[UIAlertView alloc] initWithTitle:@"修改名称\n\n\n" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
UITextField * textField=[[UITextField alloc] initWithFrame:CGRectMake(30,55, 230, 35)];
textField.tag = 5;
textField.text = str;
[textField becomeFirstResponder]; // 弹出键盘
textField.delegate=self;
[alertView addSubview:textField];
[textField release];
[alertView show];
[alertView release];
18 枚举类型的宏定义
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
from:NSObjCRuntime.h
19 NSRange 相关
NSMaxRange 返回 range 的 location 和 length 之和
20 在运行时判断类及其方法是否可用
使用 NSClassFromString,或者 获取当前系统版本,判断该版本和类可用版本
if (NSClassFromString(@"NSJSONSerialization") != nil){
/* You can use this class */
[NSJSONSerialization JSONObjectWithData:... /* Put data here */
options:... /* Put options here */ error:...]; /* Handle errors here */
} else {
/* That class is not available */
}
(If you are planning to support iOS 4 as well as iOS 5, then you can, at run-time, detect the availability of the afore- mentioned class using the NSClassFromString function, and pass the name of the class that you want to use as a parameter to this function.
From <iOS 5 Programming Cookbook>
类实例和类方法检测:
NSLog(@"instancesRespondToSelector instance method");
if ([MyGCDTestViewControllerinstancesRespondToSelector:@selector(runloop)])
NSLog(@"YES");
else
NSLog(@"NO");
// Log "YES"
NSLog(@"instancesRespondToSelector class method");
if ([MyGCDTestViewControllerinstancesRespondToSelector:@selector(classMethod)])
NSLog(@"YES");
else
NSLog(@"NO");
// Log "NO"
NSLog(@"respondsToSelector instance method");
if ([self respondsToSelector:@selector(runloop)])
NSLog(@"YES");
else
NSLog(@"NO");
// Log "YES"
NSLog(@"respondsToSelector class method");
if ([self respondsToSelector:@selector(classMethod)])
NSLog(@"YES");
else
NSLog(@"NO");
// Log "NO"
NSLog(@"MyGCDTestViewController instance method");
if ([MyGCDTestViewControllerrespondsToSelector:@selector(runloop)])
NSLog(@"YES");
else
NSLog(@"NO");
// Log "NO"
NSLog(@"MyGCDTestViewController class method");
if ([MyGCDTestViewController respondsToSelector:@selector(classMethod)])
NSLog(@"YES");
else
NSLog(@"NO");
// Log "YES"
/*
总结:
instancesRespondToSelector 能响应类的实例方法,不能响应类方法。
respondsToSelector 可以对类实例和类使用。类实例使用时,响应实例方法,不能响应类方法;类使用时,响应类方法,不响应实例方法。
ps: 两个方法对类扩展中的方法均能检测到
*/
instancesRespondToSelector 和 respondsToSelector 方法对某个类使用时,前者检测实例方法,后者检测类方法,这样可不用创建类实例。
21 SQLite 第三方库
SQLitePersistentObjects and FMDB
SQLitePersistentObjects http://code.google.com/p/sqlitepersistentobjects/
It seems a long time no update. The ZIP I downloaded is sqlitepersistentobjects_02_26_2009_snapshot. It that means It didn't update for almost three years since 02-26-2009. And SQLitePersistentObjectes doesn't support to ARC.
FMDB https://github.com/ccgus/fmdb
Well, it looks like better, updating. And support ARC.
SQLitePersistentObjectes, a good encapsulate in OO(Object-Oriented).
FMDB, you also should use SQL statements by yourself.
SQLite Manager : A Firefox plus-in GUI tool for checking split file.
/*
from http://www.cnblogs.com/likwo/archive/2011/08/03/2126400.html
相信很多人用iphone的Sqlite不会直接用C的方法,要么自己包装一层Object c的访问方法,要么用CoreData,下面我整理些目前所了结的一些Sqlite 包装类。
1.CoreData ,不用多说了,官方文档很多。
2.FMDB ,让你更熟悉使用Object c 的方法使用sql进行sqlite的操作,文件也比较小,很轻量,发现问题了,自己估计也能解决。
https://github.com/ccgus/fmdb
3. sqlitepersistentobjects ,更多的面向对象操作数据库,也非常优秀。
http://code.google.com/p/sqlitepersistentobjects/source/checkout
4. chibiorm ,FMDB的封装,解决了FMDB面向对象不足的缺点。
http://code.google.com/p/chibiorm/
svn下载地址:http://chibiorm.googlecode.com/svn/trunk/
*/
22