ios的clickios时间处理有0.1s的延迟,这个怎么处理

51778人阅读
这段代码动态的创建了一个UIButton,并且把相关常用的属性都列举了.希望对大家有用.
& //这里创建一个圆角矩形的按钮
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 能够定义的button类型有以下6种,
// typedef enum {
// UIButtonTypeCustom = 0, 自定义风格
// UIButtonTypeRoundedRect, 圆角矩形
// UIButtonTypeDetailDisclosure, 蓝色小箭头按钮,主要做详细说明用
// UIButtonTypeInfoLight, 亮色感叹号
// UIButtonTypeInfoDark, 暗色感叹号
// UIButtonTypeContactAdd, 十字加号按钮
// } UIButtonT
//给定button在view上的位置
button1.frame = CGRectMake(20, 20, 280, 40);
//button背景色
button1.backgroundColor = [UIColor clearColor];
//设置button填充图片
//[button1 setImage:[UIImage imageNamed:@&btng.png&] forState:UIControlStateNormal];
//设置button标题
[button1 setTitle:@&点击& forState:UIControlStateNormal];
/* forState: 这个参数的作用是定义按钮的文字或图片在何种状态下才会显现*/
//以下是几种状态
// UIControlStateNormal = 0, 常规状态显现
// UIControlStateHighlighted = 1 && 0, 高亮状态显现
// UIControlStateDisabled = 1 && 1, 禁用的状态才会显现
// UIControlStateSelected = 1 && 2, 选中状态
// UIControlStateApplication = 0x00FF0000, 当应用程序标志时
// UIControlStateReserved = 0xFF000000 为内部框架预留,可以不管他
* 默认情况下,当按钮高亮的情况下,图像的颜色会被画深一点,如果这下面的这个属性设置为no,
* 那么可以去掉这个功能
button1.adjustsImageWhenHighlighted = NO;
/*跟上面的情况一样,默认情况下,当按钮禁用的时候,图像会被画得深一点,设置NO可以取消设置*/
button1.adjustsImageWhenDisabled = NO;
/* 下面的这个属性设置为yes的状态下,按钮按下会发光*/
button1.showsTouchWhenHighlighted = YES;
/* 给button添加事件,事件有很多种,我会单独开一篇博文介绍它们,下面这个时间的意思是
按下按钮,并且手指离开屏幕的时候触发这个事件,跟web中的click事件一样。
触发了这个事件以后,执行butClick:这个方法,addTarget:self 的意思是说,这个方法在本类中
也可以传入其他类的指针*/
[button1 addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
//显示控件
[self.view addSubview:button1];
[button1&addTarget:self
action:@selector(alarmTimeDone:)
forControlEvents:UIControlEventTouchUpInside
addTarget:self 是链接到self,一般都这样设置
action:@selector(alarmTimeDone:) 时间处理函数
forControlEvents:UIControlEventTouchUpInside 控件事件处理的消息
//取消按钮已经添加的所有事件:(这个比较重要,若添加了两个事件& 两个事件都会被触发)
[btn removeTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];
何时释放release UIButton?
是否在dealloc中对UIButton对象进行release操作,取决于UIButton初始化的方式。
如果使用[UIButtonbuttonWithType:UIButtonTypeRoundedRect]这种方式,是不需要进行release操作的,因为这种方式是自动释放的。如果使用 [[UIButton alloc]init]的方式,则需要主动进行release释放操作。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:133402次
积分:1333
积分:1333
排名:千里之外
原创:36篇
(2)(1)(1)(11)(1)(1)(3)(1)(2)(6)(11)& 开源中国(OSChina.NET) |
开源中国社区(OSChina.net)是工信部
指定的官方社区下载地址:/ftlabs/fastclick
1、click事件为什么有延迟?
&...mobile browsers will wait approximately 300ms from the time that you tap the button to fire the click event. The reason for this is that the browser is waiting to see if you are actually performing a double tap.&
大概意思就是:从点击屏幕上的元素到触发元素的&click&事件,移动浏览器会有大约 300 毫秒的等待时间。这是因为浏览器想看看你是不是要进行双击(double tap)操作。
Mobile Safari on iOS 3 and upwards
Chrome on iOS 5 and upwards
Chrome on Android (ICS)
Opera Mobile 11.5 and upwards
Android Browser since Android 2
PlayBook OS 1 and upwards
3、什么时候不用它
fastclick不附加任何监听器在桌面浏览器上面,所以如果你的项目不是针对的移动浏览器,那么就不要使用这个插件。
Android&设备上的 google浏览器 (Chrome) 32+ 版本,在meta头信息中设置width=device-width&没有300毫秒的延时,所以也无需使用本插件。
&meta name="viewport" content="width=device-width, initial-scale=1"&
Chrome浏览器在安卓设备上的时候,设置meta头信息中&user-scalable=no&但是这样就无法让用户多点触控缩放网页了。
对于IE11 + 你可以设置&touch-action: manipulation;&来禁用通过双击放大某些元素例如:链接和按钮的,对于IE10使用&-ms-touch-action: manipulation&。
4、使用方法
引入插件的javascript文件到你的HTML网页中,像这样:
&script type='application/javascript' src='/path/to/fastclick.js'&&/script&
注意:type属性在HTML5网页中可以省略不写。
脚本必须加载到实例化fastclick在页面的任何元素之前。
实例化&fastclick 最好在body元素的前面,这是使用推荐的方法:
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
或者你使用了jquery插件,你可以这样编写:
$(function() {
FastClick.attach(document.body);
如果你使用的browserify CommonJS的模块系统或另一种风格,其&fastclick.attach&函数将返回&require('fastclick')&。作为一个结果,使用fastclick这些装载机的最简单的方法如下:
var attachFastClick = require('fastclick');
attachFastClick(document.body);
阅读(...) 评论()1663人阅读
(1)碰到报错:IBOutlet property has non-optional type UILabel
在Xcode6-beta版本碰到,& & @IBOutlet var countryLabel : UILabel = nil这句话报错,改为& & @IBOutlet var countryLabel : UILabel !即可
(2)&&&&&&&& 获取设备的参数
NSLog([[UIDevice currentDevice] name]); // Name of the phone as named by user
NSLog([[UIDevice currentDevice] uniqueIdentifier]); // A GUID like string&
NSLog([[UIDevice currentDevice] systemName]); // &iPhone OS&&
NSLog([[UIDevice currentDevice] systemVersion]); // &2.2.1&&
NSLog([[UIDevice currentDevice] model]); // &iPhone& on both devices&
NSLog([[UIDevice currentDevice] localizedModel]); // &iPhone& on both devices&
float version = [[[UIDevice currentDevice] systemVersion] floatValue];&
(3)设置searchbar半透明提示字:PlaceHolder属性
[searchBarsetPlaceholder:@&Search&];
(4)给UIView设置点击事件
-(void)initCoverView{
coverView.userInteractionEnabled=YES;//设置该view可以交互
UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAdvancedSearchView:)];
[coverView addGestureRecognizer:tapGesture];
下面实现方法showAdvancedSearchView:
- (void)showAdvancedSearchView:(UITapGestureRecognizer *)gesture{
NSLog(@&!!!!
click cover view&);
(5)去掉SearchBar边框
在SearchBar属性Bar Tint选择“Clear Color”即可。
(6)使用tableview时注意设置的大小,如果过大,则最后一行无法滑动显示
(7)textfield常用属性:
增加提示水印:textField.placeholder=@&用户名称&;
改变return类型为Done: textField.returnKeyType=UIReturnKeyDone;
用于一次性清空输入内容的靠右小叉叉:textField.clearButtonMode=UITextFieldViewModeAlways;
(8)使用代码隐藏TextField软键盘
首先在使用界面的.h文件中加入UITextFieldDelegate声明;
然后设置代理:
& & & & & &&accountTextField=[[UITextFieldalloc]initWithFrame:CGRectMake(15,0,320,44)];
& & & & & & accountTextField.delegate=self;
最后实现方法:
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
& &if (accountTextField == textField) {
& & & & [accountTextFieldresignFirstResponder];
& & return
(9)自定义颜色(RGB)
[UIColorcolorWithRed:13/255.0green:68/255.0blue:137/255.0alpha:1.0];
(10)UIPickerView高度
宽度可以改变,但是PickerView的高度是定死的216像素,无法改变
(11) 网络推送notification最多能推送256字节,超过则不予以推送。
(12) 使用动画效果CATransition
& &&CATransition *animation = [CATransitionanimation];
& & animation.duration =10.0f;
// 表示动画表示的时间开始结束缓慢,中间快
& & animation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// 这是动画类型,有很多种选择
// &kCATransitionMoveIn(覆盖原图)kCATransitionFade(淡出) kCATransitionReveal(从底部缓慢显示) kCATransitionPush(推出)
// &也可以这样表示 animation.type=@&&;&&
&& /*&过渡效果
fade&&&&&//交叉淡化过渡(不支持过渡方向)
push&&&&&//新视图把旧视图推出去
moveIn&&&//新视图移到旧视图上面
reveal&&&//将旧视图移开,显示下面的新视图
cube&&&&&//立方体翻滚效果
oglFlip&&//上下左右翻转效果
suckEffect&&&//收缩效果,如一块布被抽走(不支持过渡方向)
rippleEffect&//滴水效果(不支持过渡方向)
pageCurl&&&&&//向上翻页效果
pageUnCurl&&&//向下翻页效果
cameraIrisHollowOpen&&//相机镜头打开效果(不支持过渡方向)
cameraIrisHollowClose&//相机镜头关上效果(不支持过渡方向)
& & animation.type=kCATransitionPush;
& & animation.subtype =kCATransitionFromRight;
& & [self.view.layeraddAnimation:animationforKey:@&animation&];
& & [selftransitionFromViewController:rootViewController
& & & & & & & & & & &toViewController:domainViewController
& & & & & & & & & & & & & & &duration:1
&& & & & & & & & & & & & & & & options:UIViewAnimationCurveEaseInOut
& & & & & & & & & & & & & &animations:^(void){
& & & & & & & & & & & & & & }
& & & & & & & & & & & & & &completion:^(BOOL finished) {}];
(13) 使用pushViewController没效果
这个时候需要检查self.navigationController是否为nil,基本上无效就是因为navigationController为nil
(14) 打印CGRect
CGRect&rx = [&UIScreen&mainScreen&].bounds;
NSLog(@&%@&,NSStringFromCGRect(rx));
(15) 图片使用问题及尺寸
iPhone 6 Plus (@3x)
iPhone 6 and iPhone 5 (@2x)
iPhone 4s (@2x)
iPad and iPad mini (@2x)
iPad 2 and iPad mini (@1x)
App icon for the App Store&
1024 x 1024
1024 x 1024
1024 x 1024
1024 x 1024
1024 x 1024
Launch file or image (required for all apps)
Use a launch file (see )
For iPhone 6, use a launch file (see )
For iPhone 5, 640 x 1136
1536 x 2048 (portrait)
2048 x 1536 (landscape)
768 x 1024 (portrait)
1024 x 768 (landscape)
Spotlight search results icon (recommended)
Settings icon (recommended)
Toolbar and navigation bar icon (optional)
About 66 x 66
About 44 x 44
About 44 x 44
About 44 x 44
About 22 x 22
Tab bar icon (optional)
About 75 x 75 (maximum: 144 x 96)
About 50 x 50 (maximum: 96 x 64)
About 50 x 50 (maximum: 96 x 64)
About 50 x 50 (maximum: 96 x 64)
About 25 x 25 (maximum: 48 x 32)
Default Newsstand cover icon for the App Store (required for Newsstand apps)
At least 1024 pixels on the longest edge
At least 1024 pixels on the longest edge
At least 1024 pixels on the longest edge
At least 1024 pixels on the longest edge
At least 512 pixels on the longest edge
Web clip icon (recommended for web apps and websites)
讨厌的是,4系列竟然也使用@2x的图片,(但是3GS使用的是无后缀的图片)
所以无法区分,只能在项目中添加代码处理4系列的图片!
(16) 将testFiled设置为密码输入格式
test.secureTextEntry=YES;
(17) 解决重用TableViewCell时内容错位问题
获取Cell的方法使用如下:
//设置TableViewCell具体样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
& & UITableViewCell *cell =nil;
& &staticNSString *TableViewCellIdentifier =@&MyCells&;
& & cell=[tableViewcellForRowAtIndexPath:indexPath];//!!!!!!这一句话Important!!!!!!
& &if (cell ==nil) {
& & & & cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:TableViewCellIdentifier];
(18) UILabel换行
& &&headerLabel.lineBreakMode=UILineBreakModeWordWrap;
& & headerLabel.numberOfLines=0;
& & headerLabel.text=@&3123123&\n
4098&\n&82&;
注意顺序不要变,同时注意headerLabel的大小至少有三行,足以显示所有的字
(19)设置TableViewCell不能点击
cell.selectionStyle&=&UITableViewCellSelectionStyleNone;
(20) Alert按钮相应事件
创建Alert:
UIAlertView *updatedAlert=[[UIAlertViewalloc]initWithTitle:nilmessage:@&LOL&&delegate:selfcancelButtonTitle:@&Cancel&&otherButtonTitles:@&OK&,nil];
[updatedAlertshow];
首先在.h文件中添加&UIAlertViewDelegate&
然后在.m文件中实现如下方法即可:
-(void)alertView:(UIAlertView&*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
& &&NSLog(@& button index=%d is clicked.....&, buttonIndex);
(21) 设置UIWebView背景透明
UIWebView webView=[[UIWebView alloc]init];
[webView setBackgroundColor:[UIColor clearColor]];
webView.opaque=NO;//这句非常重要~!!!!!!!!
(22) 在项目内发送EMail
1. 在项目内导入框架MessageUI.framework;
2..h文件如下
3. 实现文件如下
(23) 使用MFMailComposeViewController发送邮件,改变其NavigationBar的背景
尝试了很多种方法都不成功,最后在AppDelegate.m方法中的didFinishLaunchingWithOptions方法中添加如下代码即可~!!!
& &&[[UINavigationBarappearance]setBackgroundImage:[UIImageimageNamed:@&navigationBarBackground.png&]forBarMetrics:UIBarMetricsDefault];
(24)在didFinishedLaunchingWithOptions方法设置text颜色时,如果需要使用阴影颜色,记得设置阴影偏移参数
& &&[[UINavigationBarappearance]setTitleTextAttributes:
&& & [NSDictionarydictionaryWithObjectsAndKeys:
& & & [UIColor
whiteColor],UITextAttributeTextColor,
& & & [UIColor
grayColor],UITextAttributeTextShadowColor,
& & & [NSValue
valueWithUIOffset:UIOffsetMake(0, -1)],UITextAttributeTextShadowOffset,
& & & [UIFont
boldSystemFontOfSize:20.0],UITextAttributeFont,nil]];
(25) 在ScrollView中使用UIWebView
#import &Foundation/Foundation.h&
#import &TNCViewController_iPhone.h&
@interface TNCViewController_iPhone ()
@implementation TNCViewController_iPhone
UIScrollView *scrollV
UIWebView *tncWebV
UIImageView *TNCbackgroundImageV
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
- (void)viewDidLoad
[super viewDidLoad];
CGRect rx = [ UIScreen mainScreen ].
float height=rx.size.
height=self.view.bounds.size.
rx.size.height=height-49-64;
scrollView = [[UIScrollView alloc] initWithFrame:rx];
scrollView.backgroundColor = [UIColor clearColor];
scrollView.delegate =
[scrollView flashScrollIndicators];
scrollView.directionalLockEnabled = YES;
TNCbackgroundImageView=[[UIImageView alloc]initWithFrame:rx];
[TNCbackgroundImageView setImage:[UIImage imageNamed:@&contentBackground.png&]];
[self.view addSubview:TNCbackgroundImageView];
[self.view addSubview:scrollView];
tncWebView=[[UIWebView alloc]initWithFrame:rx];
//获取文件路径
NSString *filePath = [[NSBundle mainBundle]pathForResource:@&tnc_chi& ofType:@&html&];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[tncWebView setBackgroundColor:[UIColor clearColor]];
[tncWebView loadRequest:request];
tncWebView.opaque=NO;
scrollView.contentSize=tncWebView.frame.
[scrollView addSubview:tncWebView];
[tncWebView release];
(26) Label中文字居中属性
NSTextAlignmentCenter
(27) 获取连接的Wifi名称
1. 在.h文件中添加 & & &#import&SystemConfiguration/CaptiveNetwork.h&
2. 方法体:
NSString *wifiName=
CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
if (!wifiInterfaces) {
NSLog(@&!!!!!!
No Wifi Connect&);
NSArray *interfaces = (__bridge NSArray *)wifiI
for (NSString *interfaceName in interfaces) {
CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
if (dictRef) {
NSDictionary *networkInfo = (__bridge NSDictionary *)dictR
NSLog(@&network info -& %@&, networkInfo);
wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
CFRelease(dictRef);
CFRelease(wifiInterfaces);
注意,上面这个方法拿到的是包括wifi名字和地址在内的数值,如果单纯的只是希望Wifi用户名,可以这样处理:
NSString *wifiName = @&Not Found&;
CFArrayRef myArray = CNCopySupportedInterfaces();
if (myArray != nil) {
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
if (myDict != nil) {
NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
wifiName = [dict valueForKey:@&SSID&];
NSLog(@&wifiName:%@&, wifiName);
(28)获取SIM卡中的MCC和MNC
1. 在.h文件中添加&
#import &CoreTelephony/CTCarrier.h&
#import &CoreTelephony/CTTelephonyNetworkInfo.h&
2.在代码中
& &&CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfoalloc]init];
& & CTCarrier *carrier = [infosubscriberCellularProvider];
& &NSString *code = [carriermobileNetworkCode];
& &NSString *country=[carriermobileCountryCode];
& &NSString *carrierName=[carriercarrierName];
& &NSString *iosCountryCode=[carrierisoCountryCode];
& & NSLog(@&!!!!!!!& code& & %@&,code);
& & NSLog(@&!!!!!!!& countrey& & %@&,country);
& & NSLog(@&!!!!!! & carrier Name& & %@&,carrierName);
& & NSLog(@&!!!!!& iosCountrycoede & %@&,iosCountryCode);
(29)使用NSNotification在两个文件之间传递参数(包括AppDelegate)
1. 在接收的文件中定义一个NotificationCenter,当接受到@“shake”时,调用方法 eraseView
& &&[[NSNotificationCenterdefaultCenter]addObserver:self&
& & & & & & & & & & & & & & & & & & & & & & & & & & & & &selector:@selector(eraseView)&name:@&shake&&object:nil];
2. 实现方法eraseView
-(void) eraseView
& & NSLog(@&!!!!!!!!& getNotification !!&);
& & wifiNameLabel.text=@&YEYEEYEYEYEYE&;
3. 在发出文件中:
& & & &&[[NSNotificationCenterdefaultCenter]postNotificationName:@&shake&&object:self];
(30)使用Reachability检测Wifi使用情况(动态检测开启和关闭)
要注意~!!!Reachablity3.0以上的版本才支持ARC!所以要根据你的项目需求导入不同的Reachability
1. 在项目中导入&Reachability.h 和 Reachability.m&
2. 在项目的framework中导入SystemConfiguration.framework
3.在需要使用的.h文件中 &#import&Reachability.h&
4.在程序中实现:
& & Reachability *r = [ReachabilityreachabilityWithHostName:@&&];
& & switch ([rcurrentReachabilityStatus]) {
& & & & caseNotReachable://No Wifi
& & & & & &//没有网络连接
& & & & & &break;
& & & & caseReachableViaWWAN:
& & & & & &//使用<span style="color:#G网络
& & & & & & NSLog(@&!!!!!& Use& 3G&);
& & & & & &break;
& & & & caseReachableViaWiFi:
& & & & & &//使用WiFi网络
& & & & & & NSLog(@&!!!!$$$$$$$$$$$$$$!!!& use WIFI&);
& & & & & &break;
例如在IOS7中,可以使用快捷上拉栏开启和关闭Wifi功能,所以要在appDelegate文件中对动态开启关闭Wifi功能进行检测
- (BOOL)application:(UIApplication&*)application didFinishLaunchingWithOptions:(NSDictionary&*)launchOptions
& &&[[NSNotificationCenterdefaultCenter]addObserver:self
&& & & & & & & & & & & & & & & & & & & & & &selector:@selector(reachabilityChanged:)
&& & & & & & & & & & & & & & & & & & & & & & & &name:kReachabilityChangedNotification
&& & & & & & & & & & & & & & & & & & & & & & &object:nil];
& & hostReach = [[ReachabilityreachabilityWithHostName:@&&]retain];
& & [hostReachstartNotifier];
然后在方法reachbilityChanged中监听Wifi状态的改变
- (void)reachabilityChanged:(id)note {
//& & Reachability* curReach = [note object];
& & NSParameterAssert([hostReachisKindOfClass: [Reachabilityclass]]);
& & NetworkStatus status = [hostReachcurrentReachabilityStatus];
& & [[NSNotificationCenterdefaultCenter]postNotificationName:@&changeText&
& & & & & & & & & & & & & & & & & & & & & & & & & & & &object:self];
& &if (status ==NotReachable) {
& & & &UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@&AppName&
& & & & & & & & & & & & & & & & & & & & & & & & & & & &message:@&NotReachable&
&& & & & & & & & & & & & & & & & & & & & & & & & & & &delegate:nil
& & & & & & & & & & & & & & & & & & & & & & &cancelButtonTitle:@&YES&otherButtonTitles:nil];
& & & & [alertshow];
& & & & [alertrelease];
& & & & [[NSNotificationCenterdefaultCenter]postNotificationName:@&changeText&
& & & & & & & & & & & & & & & & & & & & & & & & & & & & & &object:self];
& & }else {
(32) UI平移动画效果
& &&[UIViewanimateWithDuration:0.5animations:^{
& & & & [preferButtonsetTransform:CGAffineTransformMakeTranslation(preferbtnRx.origin.x-40,preferbtnRx.origin.y)];
& & & & [locationButtonsetTransform:CGAffineTransformMakeTranslation(preferbtnRx.origin.x-40,preferbtnRx.origin.y)];
其中,preferbtnRx是CGRect(没有初始化的),该效果是这两个按钮向左水平平移40距离
(34)只改变NavigationBar返回键的内容,而不改变其样式
注意,要在其父类中实现下面代码!
& &&UIBarButtonItem *backbutton = [[UIBarButtonItemalloc]init];
& & backbutton.title =@&返回&;
& & self.navigationItem.backBarButtonItem =
& & [backbuttonrelease];
如果是实现按钮的自定义,关键字是self.navigationItem.left.......
& (35) 新建项目在Iphone5运行时出现上下两条黑边,只要添加尺寸为320*568的黑色图片即可(项目默认3.7寸屏幕),且命名为Default-568h@2x.png
&(36) 实现数字小时钟
#import &ViewController.h&
@interface ViewController ()
@implementation ViewController
@synthesize timeL//It&#39;s a UILabel
- (void)viewDidLoad {
[super viewDidLoad];
[self setTime];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(setTime:) userInfo:nil repeats:YES];
-(void)setTime:(id)sender{
NSDate *curtime = [NSDate date];
NSDateFormatter *formatterCur1 = [[NSDateFormatter alloc] init];
[formatterCur1 setDateFormat:@&yyyy-MM-dd HH:mm:ss&];
NSString *timestr1 = [formatterCur1 stringFromDate:curtime];
timeLabel.text=timestr1;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
//页面将要进入前台,开启定时器
-(void)viewWillAppear:(BOOL)animated
//开启定时器
[timer setFireDate:[NSDate distantPast]];
//页面消失,进入后台不显示该页面,关闭定时器
-(void)viewDidDisappear:(BOOL)animated
//关闭定时器
[timer setFireDate:[NSDate distantFuture]];
(37) 禁止横屏
在AppDelegate中添加:
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow
& & returnUIInterfaceOrientationMaskPortrait;
(38)popoverController只能在iPad上使用,如果想要在iPhone上使用,参考链接的代码 &
http://download.csdn.net/detail/eduask_xia/4287865
(40)使用sqlite3执行查询语句
其中,databaseX和databaseY是double类型,表testing中包含x,y,z,en,ch数&#20540;,x,y,z为int,en,ch为text
NSString * selectSql = [NSStringstringWithFormat:@&select
* from testing where (abs(x-%f)&=250) and (abs(y-%f)&=250)&,databaseX,databaseY];
& & & & & & NSLog(@&dataExisted query_sql:%@&,selectSql);& & & & & &&
& & & & & &sqlite3_stmt *
& & & & & &if (sqlite3_prepare_v2(database, [selectSqlUTF8String], -1,
&statement,nil)==SQLITE_OK)
& & & & & & {
& & & & & & & &while (sqlite3_step(statement)==SQLITE_ROW)//SQLITE_OK
SQLITE_ROW
& & & & & & & & {
& & & & & & & & & &int x=sqlite3_column_int(statement,0);
& & & & & & & & & &int y=sqlite3_column_int(statement,1);
& & & & & & & & & &int z=sqlite3_column_int(statement,2);
& & & & & & & & & & NSString *en=[[NSStringalloc]initWithCString:(char
*)sqlite3_column_text(statement,3)encoding:NSUTF8StringEncoding];
& & & & & & & & & & NSString *ch=[[NSStringalloc]initWithCString:(char
*)sqlite3_column_text(statement,4)encoding:NSUTF8StringEncoding];
&& & & & & & & & & &
& & & & & & & & & & NSLog(@&row&&x %i, y %d,z %d, en&& %@, ch& %@&,x,y,geo_ref,dn_en,dn_ch);
& & & & & & & & }
& & & & & & }
(42)获得系统时间
& &&NSDate * senddate=[NSDatedate];
& & NSDateFormatter *dateformatter=[[NSDateFormatteralloc]init];
& & [dateformattersetDateFormat:@&YYYYMMdd-HH-mm-ss&];
& &NSString * dataString=[dateformatterstringFromDate:senddate];
要注意!!重要事情说三遍!重要事情说三遍!重要事情说三遍!
如果单纯是NSDate date拿到的时间是&#26684;林&#23612;治时间,但是经过dateformatter转变之后,String就变成了系统时间~!相当神奇!
(43)去掉NSString首尾空&#26684;
[signalStrengthLabel.textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];
(44)NSMutableString添加URL参数
& &&NSMutableString *urlString=[[NSMutableStringalloc]initWithString:requestUrl];//requestUrl=&http//xx.xx.xx.xx/xxxx/xx.php&
& & [urlStringappendString:@&?&];
& & [urlStringappendFormat:@&version=%i&,version];//version=1
& & [urlStringappendFormat:@&&Date=%@&,date];//data =@&&
& & [urlStringappendFormat:@&&Latitude=%.7f&,latitude];//latitude=23.1214134
(45)使用UTF-8编码NSString
[NSString&stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
(46)设置带有NavigationBar的跳转页面标题
这时候只能设置
& & [self.navigationItemsetTitle:@&TESTTEST&];
别的属性都不管用
(47)&&&&&&& 程序崩溃&IOS&EXC_BAD_ACCESS
这个问题是最不好排查的,连NSLog都不管用,因为在控制台上根本看不到是那个Object出了问题
90%的情况都是因为对某个已经释放的类进行release操作
(48)&&&&&&IOS时间转化为NSString
&NSDate* today = [NSDatedate];
& &NSLog(@&%@&,today);
& &NSDateFormatter*df = [[NSDateFormatteralloc]init];
& &[dfsetDateFormat:@&yyyy-MM-dd HH:mm:ss&];
&NSString* s1 = [dfstringFromDate:today];
(49)&&&&使用sqlite3时提示database is locked解决方法
我在这里并没有使用多线程,我的问题是select语句没有进行reset操作
& & & &sqlite3_reset(selectStmt);
& & & &if(selectStmt)sqlite3_finalize(selectStmt);
添上这两行就好
(50) & &UIActionSheet简单使用方法
1. 在.h文件中引用ActoinSheetDelegate
&UIActionSheetDelegate&
2. 实现ActionSheet
&UIActionSheet *sheet=[[UIActionSheetalloc]initWithTitle:nildelegate:selfcancelButtonTitle:@&cancel&destructiveButtonTitle:[NSString&stringWithFormat:@&Test1
%@&,showContent]otherButtonTitles:[NSStringstringWithFormat:@&Test2
%@&,showContent],[NSStringstringWithFormat:@&Test3 %@&,showContent],nil];
&[sheetshowInView:self.view];
3. ActionSheet按钮的监听
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
& &if (buttonIndex ==0) {
& & & &NSLog(@&00000&);
& & }elseif (buttonIndex ==1) {
& & & &NSLog(@&11111&);
& & }elseif(buttonIndex ==2) {
& & & &NSLog(@&222222&);
& & }elseif(buttonIndex ==3) {
& & & &NSLog(@&33333&);
(51) & 删除本地文件
NSFileManager *fileManager=[NSFileManager defaultManager];
NSError *errorFileD
if ([fileManager fileExistsAtPath:localFilePath]){
[fileManager removeItemAtPath:localFilePath error:&errorFileDelete];
(52) & UIImage显示图片用法
1. 显示已经导入项目的资源
UIImage *image=[UIImage imageNamed:@&PictureName&];
2. 显示绝对路径的图片(用于显示下载图片后储存在本地的图片)
&UIImage *personImage=[UIImageimageWithContentsOfFile:photoPath];
3. 显示URL地址图片
NSURL *url = [NSURL URLWithString:@&图片地址&];&
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];&
(53) & UIImage实现圆形图片效果
UIImage *Image=[UIImage imageWithContentsOfFile:@“XXXXX”];
UIImage *scaledImage = [Image scaleToSize:CGSizeMake(100, 100)];
Icon.image=scaledI
[Icon.layer setCornerRadius:scaledImage.size.width/2];
[Icon.layer setMasksToBounds:YES];
其中scaledImage的scaleToSize中的参数能够决定图片四个角的弧度,弧度越大,越接近圆形
另外Icon是UIImageView
(54) 页面左右滑动手势监听----即手指向左或向右滑动时,页面翻页效果
1. ViewdidLoad中添加代码:
UISwipeGestureRecognizer *leftSwitch=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(switchLeft:)];
leftSwitch.direction=UISwipeGestureRecognizerDirectionL
[self.view addGestureRecognizer:leftSwitch];
UISwipeGestureRecognizer *rightSwitch=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(switchRight:)];
rightSwitch.direction=UISwipeGestureRecognizerDirectionR
[self.view addGestureRecognizer:rightSwitch];
2. 在类中添加代码:
- (void)switchLeft:(UISwipeGestureRecognizer *)sender
[self.myNavController switchPageTo:0];
- (void)switchRight:(UISwipeGestureRecognizer *)sender
&pre name=&code& class=&objc&&
[self.myNavController switchPageTo:2];}
(55) pushViewController动画代码:
CATransition *transition = [CATransition animation];
&#160; &#160; transition.duration = 0.3f;
&#160; &#160; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
&#160; &#160; transition.type = kCATransitionP
&#160; &#160; transition.subtype = kCATransitionFromR
&#160; &#160; transition.delegate =
&#160; &#160; [self.contentView.layer addAnimation:transition forKey:nil];
(56) 在ARC模式中使用delegate应该如下:
& __strong NSObject &PageDelegate& *pageD
@property (retain, nonatomic) id pageD
(57) 打印BOOL&#20540;方法
& &&NSLog(@&isON:%@&,isEnable?@&YES&:@&NO&);
(58) 计算可变UILabel的行数
其中在此之前label已经实例化
- (int)lineCountForLabel:(UILabel *)label {
CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX);
CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap];
return ceil(size.height / label.font.lineHeight);
(59) 限制TextView输入字数
首先设置了textView.delegate=self
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSString *new=[textView.text stringByReplacingCharactersInRange:range withString:text];
//To get the maxture of text
int max=[StringUtil getMessageMaxNumber:text];
NSInteger res=max-[new length];
if (res&=0){
return YES;
NSRange rg={0,[text length]+res};
if (rg.length&0) {
NSString *s=[text substringWithRange:rg];
[textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
return NO;
(60)&&&&&&&&& textfield中监听回车事件
- (BOOL) textfieldShouldReturn:(UITextfield) textField{
&&& return YES;
(61)&& UITextAlignmentCenter在6.0中被弃用
改为NSTextAlignmentCenter即可
(62)&&& 重写Navigationbar的Back方法
其实不算是重写,因为找不到这个方法来覆盖,所以先自定义一个UIBarButtonItem,添加方法,然后将其设置为self.navigationItem.leftButton而非BackButton,然后再自定义的方法里添加想要的效果即可。
(63)&&&& 自定义UIBarButtonItem背景图
初始化的方法为
UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithImage.........];
但是不成功,显示出来的item为橙色(网上也有蓝色显示的)
原因在于Image尺寸貌&#20284;被压缩到最小了,所以看不到。
应该这样设置:
UIImage *image=[UIImage imagenamed:@....];
image=[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
(64)&&&& IOS模拟器出现FBSOpenApplicationErrorDomain, code=4&错误
选中IOS模拟器,然后iOS Simulator -& Reset Content and Settings.....即可
(65)判断APP是否在设备上首次安装
在AppDelegate方法
-&(BOOL)application:(UIApplication&*)application&didFinishLaunchingWithOptions:(NSDictionary&*)launchOptions中添加下面片段片段:
if (![[NSUserDefaults standardUserDefaults] boolForKey:@&firstInstall&]) {
NSLog(@&第一次启动!&);
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@&firstInstall&];
NSLog(@&非第一次启动&);
(66)使用storyboard,使用代码改变启动初始页面(配合检查是否初次安装该APP,决定是否显示引导动画)
在AppDelegate方法
-&(BOOL)application:(UIApplication&*)application&didFinishLaunchingWithOptions:(NSDictionary&*)launchOptions中添加下面片段片段:
NSString *startPageId=@&&;
if (![[NSUserDefaults standardUserDefaults] boolForKey:@&firstInstall&]) {
//push welcome page
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@&firstInstall&];
startPageId=@&WelcomePageIdentifier&;
NSLog(@&非第一次启动&);
startPageId=@&BookTabbarIdentifier&;
self.window.rootViewController=[self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:startPageId];
return YES;
在storyboard里面,给引导页面WelcomePageViewController添加了Storyboard&ID& “WelcomePageIdentifier”
给使用界面TabbarController添加了Storyboard ID “BookTabbarIdentifier”
上述代码的逻辑是:如果是很初次安装,那么App的起始界面就是WelcomePage,否则就以TabbarController作为rootView界面
(67)&使用代码退出App(使用动画效果,否则看上去像闪退)
NSLog(@&Clicked Cancel&);
AppDelegate *appDelegate=[UIApplication sharedApplication].
UIWindow *window=appDelegate.
[UIView animateWithDuration:2.0 animations:^{
window.alpha=0.0;
window.frame=CGRectMake(0, window.bounds.size.width, 0, 0);
} completion:^(BOOL finished){
(68)& 关掉某个文件的ARC模式
在Build Phases中搜索某文件的名字,选中一个/几个后回车,出现输入框,输入-fno-objc-arc,回车即可
(69)&& 获取系统时间
NSDate *currentTime=[NSDate date];
NSCalendar *calender=[NSCalendar currentCalendar];
unsigned int unitFlags=NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarU
NSDateComponents *dateComponent=[calender components:unitFlags fromDate:currentTime];
int year=[dateComponent year];
int month=[dateComponent month];
int day=[dateComponent day];
NSString *sTime=[NSString stringWithFormat:@&%d%d%d&,year,month,day];
NSLog(@&Current time:%@&,sTime);
如果需要精确到时,分,秒的话,在unitFlags后面继续添加代码:| NSHourCalendarUnit| NSMinuteCalendarUnit|NSSecondCalendarUnit;
然后再获取时分秒
int hour = [dateComponent hour];
int min = [dateComponent minute];
int sec = [dateComponent second];
(70)&&& 使用代码绘制渐变颜色(由上至下渐变)
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, 0, 宽, 高);
gradient.colors = [NSArray arrayWithObjects:
(id)[UIColor blackColor].CGColor,
(id)[UIColor grayColor].CGColor,
(id)[UIColor blackColor].CGColor,
[self.view.layer insertSublayer:gradient atIndex:0];
(71)&&&& 如何将用户发送过来的crash日志中二进制码符号化(解析crash文件报错行)
以项目名为Test.app为例
1.&将拿到的crash日志改为后缀名为.crash的文件
2.&打开Xcode,Window, Organazier,&选中Test文件,右键,Show in Finder,&选中显示的Test.xcarchive,右键,显示包含内容,将显示的Test.app.dSYM拷贝出来
3.&将你build的IPA文件和刚才找到的.dSYM文件以及用户发送过来的.crash文件放置在同一个文件夹内
4.&Xcode,Window,Device,(这个时候要连接设备),选择view logs,等待Xcode将设备的所有Log读取完毕之后,将用户的Crash文件拖拽到Logs当中,就可以看到看不明白的二进制码被符号化成相应的方法,类别,出错的行数等。
(72)&&&& 延迟几秒调用某个方法
直接使用下面代码即可,完全不需要使用定时器
即:定时器使用一定是为了某个重复调用
[self performSelector:@selector(setTime:) withObject:nil afterDelay:20.0];
然后在方法 - (void) setTime:(id)sender&中完成需要的动作即可
(73)&&&&& SQL中limit offset用法
举例说明:
select * from test where xx=? order by XX desc limit 10 offset 20
说明跳过前20条记录,开始取10条记录
(74)&&&&&& 使用Delegate时报错Cannot find protocal ......
A类中定义了protocal,想要在B类中使用,出现这个问题是因为两个类的.h文件相互import,取消掉其中一个即可
(75) & & & 使用TableView必须实现的方法
#pragma TableView
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
return [resourceArray count];
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @&Identifier&;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
NSString *titleString=[resourceArray objectAtIndex:indexPath.row];
label.text=titleS
(76) & & && 自定义使用Log(如PLog)并控制其打印
首先,创建一个.pch文件,命名规范为:&项目名称_Prefix.pch
然后将下面的代码拷贝到新文件中:
#define DEBUG 1
#ifdef DEBUG
#define PLog(...) NSLog(__VA_ARGS__)
#define debugMethod()NSLog(@&%s&,__func__)
#define NSLog(...)
#define debugMethod
然后会用PLog打印,如果想要关闭,那么将第一行#define&DEBUG 1注销掉即可
(77) & & &&& 点击Button后修改其标题,修改一瞬间后变回原来的标题
这是个很纠结的问题,我折腾了一下午,不能单纯的xxButton.titleLabel.text=@&&这样修改,而应该是:
setTitle:ForState:UIControlStateNormal这样来设置才能达到需要的效果
(78) & & &&&&& 发邮件、打电话
&&&&&&&&NSString&*mailAddress=@&mailto:&;
&&&&&&&&[[UIApplication&sharedApplication]&openURL:[NSURL&URLWithString:mailAddress]];
&&&&NSString&*callNumber=@&tel:&;
&&&&[[UIApplication&sharedApplication]&openURL:[NSURL&URLWithString:callNumber]];
(79) & & &&&& ios项目引入第三方framework(如facebook)
引入第三方的framework方法和内部库一致,但是要注意必须将framework拷贝到项目文件夹内
(80) & & &&&& Storyboard button设置圆角
选中Button, 在右边的编辑框中找到User Defined Runtime Atributes(点击菜单栏第三个按钮可看到)
点击“&#43;”添加属性“layer.cornerRadius”,Type选择Number,然后填写Value&#20540;,默认按钮高度的话,value是5就有一个小圆角,慢慢试吧
要注意的是,如果该Button添加了图片作为背景,那么单纯设置layer.cornerRadius则没有作用,还需要多添加一个设置:setMasksToBounds YES 才会起作用
(81) & & &&&& Label文字添加下划线
NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString: [NSString stringWithFormat:@&Forget Password?&]];
NSRange contentRange = {0,[content length]};
[content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range:contentRange];
Label.attributedText =
(82) & & &&&& Storyboard跳转后,如何传&#20540;
利用Segue在Storyboard的两个ViewController跳转时传&#20540;
1. 先连线好跳转,并选择Modal或Push模式
2. 点击连线(Segue),并在Identifier中给其命名
3.实现下面代理方法
# pragma Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@&MobileSegue&]) {
id sendSegue=segue.destinationViewC
[sendSegue setValue:@&Mobile& forKey:@&type&];
} else if ([[segue identifier] isEqualToString:@&EmailSegue&]){
id sendSegue=segue.destinationViewC
[sendSegue setValue:@&Email& forKey:@&type&];
//EmailSegue/MobileSegue 就是你定义的Segue Identifier
(83) & & &&&&& 设置键盘类型
如果需要动态设置键盘类型,可以参考下面代码
否则在storyboard上就可以选择textfield或textview的键盘类型,回车键类型等
TextIP1.keyboardType = UIKeyboardTypeNumberP
UIKeyboardTypeAlphabet(Alphabet字母)
UIKeyboardTypeASCIICapable
UIKeyboardTypeDefault
2、数字键盘
UIKeyboardTypeDecimalPad (Decimal十进制)
3、电子邮箱键盘
UIKeyboardTypeEmailAddress
4、没有符号的英文键盘
UIKeyboardTypeNamePhonePad
5、没有小数点的数字键盘
UIKeyboardTypeNumberPad
6、全键盘的数字键盘
UIKeyboardTypeNumbersAndPunctuation
7、带符号的数字键盘
UIKeyboardTypePhonePad
8、推特键盘
UIKeyboardTypeTwitter
(84) & & &&&&&& iPhone6/6s 模拟器键盘不弹出解决方法
在xcode6中, 模拟器中的键盘和电脑的键盘可以进行绑定or解除绑定,打开模拟器,在最上面的菜单栏中,选择hardware,然后选择keyboards,有三个选项, 依次都勾选就行了。(注意:第三个选项在点击之后,实际已勾上了,但显示未勾上,但实际已经奏效了,这可能是xcode6的一个显示上的bug)
(85) & & & &监听Textfield输入内容变化
[self.firstTextF addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];-(void)textFieldDidChange:(id)sender
NSLog(@&%@&, self.firstTextF.text);
(86) & & & &转菊花插件的使用UIActivityIndicatorView
使用方式就是
UIActivityIndicatorView *testActivityIndicator = [UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]];
testActivityIndicator.center = CGPointMake(100.0f, 100.0f);//只能设置中心,不能设置大小
[testActivityIndicator setFrame = CGRectMack(100, 100, 100, 100)];//不建议这样设置,因为UIActivityIndicatorView是不能改变大小只能改变位置,这样设置得到的结果是控件的中心在(100,100)上,而不是和其他控件的frame一样左上角在(100, 100)长为100,宽为100.
[self addSubview:testActivityIndicator];
testActivityIndicator.color = [UIColor redColor]; // 改变圈圈的颜色为红色; iOS5引入
[testActivityIndicator startAnimating]; // 开始旋转
[testActivityIndicator stopAnimating]; // 结束旋转
[testActivityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏
(87) & & & &自定义时间的倒计时
其实也是使用了Timer,可以参考之前的Timer的例子
重点是每秒调用的方法不再是获取当前时间,以倒数30分钟为例,
设置int counter=S)
int minute =counter/60;
int second=counter%60;
然后将minute和second显示出来即可
(88) & & && 使用presentViewController 跳转黑屏
在ios8中使用[self presentViewController:controller animated:YES completion:^{}];跳转后黑屏
主要是因为使用了storyboard,然后还使用从前的方法获取Controller alloc init则无法与storyboard上的ViewController联系在一起
所以这个时候要使用下面的方法获取controller:
mainViewController&*mainView=[self.storyboard&instantiateViewControllerWithIdentifier:@&ID&];
然后再跳转即可
(89) & & &&& ScrollView滚动到指定位置
CGPoint scrollPoint=CGPointMake(scrollViewRect.size.width, 0);
[scrollView setContentOffset:scrollPoint animated:YES];
(90) & & &&&& App注册Notification并获取其Token
1. 首先注册App的Profile的时候记得选择PushNotification类型的,否则不行
2. 代码部分全部在AppDelegate中完成
(1) 注册Notification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FBLoginView class];
//get stored missing call count-设置提醒标记
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
//Register Notification
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
// Register for iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
// Register for iOS & 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
return YES;
(2) 获取Token
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
NSLog(@&设备令牌: %@&, deviceToken);
NSString *tokeStr = [NSString stringWithFormat:@&%@&,deviceToken];
if ([tokeStr length] == 0) {
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
NSLog(@&获得令牌失败: %@&, error);
(91) & & &&&&& 读取plist文件内容(与项目的info.plist处于同级文件夹内)
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@&plistdemo& ofType:@&plist&];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(@&%@&, data);//直接打印数据。
plist名为plistdemo.plist
重要事情说三遍!重要事情说三遍!重要事情说三遍!!
用上述方法初始化plist文件的时候,要保证里面已经有内容了!否则无论如何都写不进去,因为文件还没有创建啊!他是nil啊!
所以要判断data是否为nil,如果为nil则初始化NSMutableDictionary的时候直接塞数据进去即可
然后[plistDic writeToFile:filePath atomically:YES];就可以写进去了
另外还有一个拿到路径的方法,貌&#20284;这个方法只能读,不能写,因为[NSBundle mainBundle]拿到的路径是只读的
Boolean result =
NSString *filePath = [[self libraryPath] stringByAppendingPathComponent:@&test.plist&];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setObject:dict forKey:keyString];
result=[plistDict writeToFile:filePath atomically:YES];
NSLog(@&save result=%@&, result? @&success&:@&fail&);
NSDictionary *getTestDic=[[NSDictionary alloc] initWithContentsOfFile:filePath];
这样就可以愉快的存储和读取了
(92) & & & & & 获取本地APP版本号以及App Store上版本号,确定是否要升级
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
NSString *currentVersion = [infoDic objectForKey:@&CFBundleShortVersionString&];
NSLog(@&current Version:%@&,currentVersion);
NSString *url=[NSString stringWithFormat:@&%@%@&,@&/lookup?id=&,appID];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id
_Nonnull responseObject) {
NSArray *array = responseObject[@&results&];
NSDictionary *dict = [array lastObject];
NSString *storeVersion=[dict objectForKey:@&version&];
NSLog(@&当前版本为:%@&, dict[@&version&]);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
(93) & & & & && 设置App多语言(国际化/本地化)
0.& 首先在project-& Localization中添加你需要的语言,例如Chinese Traditional
1. 首先添加一个strings文件,名为Localizable.strings,添加方法为:add-&resource-&strings,命名一定要为Localizable.strings
2. 选中Localizable.strings,View-&Utilities-&Show File Inspector
3. 然后就可以生成相应的strings
例如Localizable.strings(English)/Localizable.strings(Chinese(Traditional))
然后在二者定义一样的Key,不一样的内容
“Test”=&Test&
&Test&=&测试&
这样系统会根据手机的语言系统显示相应的内容
(94) & & & & && Storyboard的语言多样化
选中Storyboard,应该在以第一选项卡中找到Localization标签,
然后它会自动生成中文和英文的纯string文本,修改string的内容即可
可以参考这个文章
/articles/Zr67Nb2
(95) & & & & && Storyboard添加Entyy point
选中设置的ViewController,选择第四个tag,找到“Is Initial View Controller”标签选中即可
参考/152.html
(96) & & & & &&& 代码更改NavigationBar的标题
self.navigationItem.title=@&Test&即可
(97) & & & & &&&& 使用StoryBoard更改点击按钮时的背景图片
1 在Button菜单栏中的Type中将类型改为“Custom”而非默认的“System”
2. State Config为“Default”时,添加普通状态下的按钮背景图片
3. 将Statue Config的&#20540;改为“HightLighted”,然后Background中添加点击按钮时显示的背景图
4. 将Statue Config&#20540;改为“Selected”,然后Background中添加点击按钮时显示的背景图
如果是使用代码自定义按钮不同状态下的背景图片的话,如下两行代码即可:
[contactBookBtn setBackgroundImage:[UIImage imageNamed:@&left1.png&] forState:UIControlStateNormal];
[contactBookBtn setBackgroundImage:[UIImage imageNamed:@&left2.png&] forState:UIControlStateSelected];
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:30965次
排名:千里之外
原创:48篇
转载:13篇
译文:12篇
评论:12条
(2)(1)(1)(2)(1)(2)(3)(2)(2)(2)(1)(3)(3)(1)(1)(3)(4)(3)(1)(1)(3)(1)(8)(3)(7)(7)(5)

我要回帖

更多关于 批处理 延迟时间 的文章

 

随机推荐