您的位置:首页 > 移动开发 > IOS开发

iOS开发小技巧(最后更新2014.11.25)

2014-08-01 08:23 337 查看
1.去输入内容空格方法

(1)系统去首尾空格方法,使用NSString中的str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]方法只是去掉左右两边的空格;
(2)替换的方法,使用NSString *strUrl = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""];可以去掉空格,注意此时生成的strUrl是autorelease属性的,不要妄想对strUrl进行release操作。
2.表单自动滚动

方法有多种,你可以用scrollview,设置contentsize是一个稍大于frame,当键盘出现,减小frame,滚动输入框视图frame为可见,键盘隐藏,还原frame。你可能得添加键盘事件通知,并且需要用到:-
(void)scrollRectToVisible:(CGRect)rect
animated:(BOOL)animated;

3.设置状态栏颜色为白色

状态栏默认为黑色,只要将plist中加入UIViewControllerBasedStatusBarAppearance 的布尔值NO就可以了,当然还需要将

[[UIApplication
sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

4.字符串截取操作

这个有些多,请移步(/article/4006475.html

5.iOS时间那点事

这个有人写过了,请移步查看(http://www.kankanews.com/ICkengine/archives/24425.shtml
6.iOS定位城市
a.使用CoreLocation 定位得到经度和纬度
b.在-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation代理方法中使用CLGeocoder的reverseGeocodeLocation: :方法解析
c.在b中解析方法的完成回掉块completionHandler:^(NSArray *placemarks, NSError *error)中得到Country(国家) State(城市) SubLocality(区)
详情如下:

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

[locationManager stopUpdatingLocation];
NSLog(@"location ok");

CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {

NSDictionary *test = [placemark addressDictionary];
//  Country(国家)  State(省)  SubLocality(区)城市需要用place mark.locality获得
NSLog(@"%@", [test objectForKey:@"State"]);
}
}];
}
7.一定要注意解耦和继承的使用,可以减少代码,增加复用。

8.tableViewCell 选中颜色设置cell.selectionStyle属性,值为枚举,可设为无色UITableViewCellSelectionStyleNone

9.iOS模拟器汉语输入法,可以通过设置,输入法,添加输入法,选中中文简体,之后键盘就支持中文输入了。

10.刷新某行cell方法NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:1 inSection:0];

NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];

[myTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimation]

11. 字符串,整数,浮点数之间的相互转换,看(/article/3556900.html

12.字符串NSString 判空[text lenght] == 0

----------------------------------8.6------------------------------------------

13.iOS生成随机数方式:① srand((unsigned)time(0)); int i = rand() % 5;② srandom(time(0)); int i = random() % 5; ③ int i = arc4random() % 5 ;

14.修改iOS应用名称:xxx-info.plist文件Bundle display name,修改对应的值为应用名称(默认为${PRODUCT_NAME})

15.字典操作:得到所有键值[dict allKeys]; [dict allValues]; 遍历:①,for in 方式,②for(;;)方式[mdict objectForKey:[[mdict allKeys]objectAtIndex:index]]

----------------------------------8.7------------------------------------------

16.使按钮文字居左方法是:btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft; 并不是:btn.titleLabel.textAlignment = NSTextAlignmentLeft;

17.有时候在viewDidLoad里面得不到通过属性赋值传过来的值,这时你可以尝试在viewWillAppear或viewDidAppear中去得。

----------------------------------8.12------------------------------------------

18.ios 操作plist文件。读取用[[NSMutableDictionary alloc] initWithContentsOfFile:_plistPath];或 [[NSMutableArray alloc] initWithContentsOfFile:_plistPath];文件路径用: [[NSBundle mainBundle] pathForResource:@"xxxx" ofType:@"plist"];来读取,写入用:[dict writeToFile:_plistPath atomically:YES];

----------------------------------8.14------------------------------------------

19.UISlider 显示整数int i=(int)(slider.value +0.5f);

----------------------------------8.18------------------------------------------

20.ios 禁止横屏显示:- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return UIInterfaceOrientationMaskPortrait; }

----------------------------------8.19------------------------------------------

21.UILabel默认为居左显示,想让居中方式为:label.textAlignment = UITextAlignmentCenter;(label.textAlignment =

NSTextAlignmentCenter)
----------------------------------8.22------------------------------------------

22.让button 文字居左:btn.contentHorizontalAlignment = UIControlContentHorizonAlignmentLeft; icon显示颜色设置:[btnsetTintColor:[UIColor xxxx]];
----------------------------------9.1------------------------------------------

23.给UITextField加上背景视图方式:http://awayli.blog.163.com/blog/static/2002970772011111525655552/当然最简单就是直接新加一个UIImageView
在输入框附近即可。
24.有时候使用CGRectGetMaxY(field.frame)的方式来得到X,Y偏移量很不错,此外还有CGRectGetMaxX(<#CGRect rect#>)等。
----------------------------------9.2------------------------------------------

25.ALAsset *lookAsset;

UIImage* resourceImage = [UIImage imageWithCGImage:[[lookAsset defaultRepresentation] fullScreenImage]];

此时取出的resourceImage会横竖屏颠倒显示,解决方法如下:
UIImage *fullImage = [UIImage imageWithCGImage:[lookAsset.defaultRepresentation fullScreenImage]

scale:[lookAsset.defaultRepresentation scale] orientation:

(UIImageOrientation)[lookAsset.defaultRepresentation orientation]];
----------------------------------9.5------------------------------------------

26.IOS7中设置状态栏隐藏方法,在plist中加入View controller-based status bar appearance为NO,然后在需要隐藏状态了的ViewController中重写一下方法prefersStatusBarHidden返回NO即可。示例:

//ADD  FOR iOS7(隐藏状态栏)
- (BOOL)prefersStatusBarHidden
{
return YES;
}

参考:http://stackoverflow.com/questions/17763719/status-bar-wont-disappear

----------------------------------9.6------------------------------------------

27.设置UICollectionView的cell的默认大小用:flowLayout.itemSize =CGSizeMake(70,70);,自定义大小用:

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

return CGSizeMake(kUpCellWith,kUpCellHeight);
}
默认间距设置用:flowLayout.minimumInteritemSpacing = 0;

----------------------------------11.8------------------------------------------

28.删除uitableview或者uicollectionview里面的数据方法。多选删除的时候,可以创建一个数组,记录下来选中元素的下标NSIndexPath,然后将其进行从大到小排序,然后进行视图数据源中对应位置的元素删除,重新刷新UI即可,同时可以进行网络删除。附排序方法:

#import "NSArray+Sort.h"

@implementation NSArray (Sort)

- (NSArray *)sortedNSIndexPathArrayByDescending{

NSComparator descendingSort = ^(NSIndexPath *m, NSIndexPath *n){

if (m.row < n.row) {
return (NSComparisonResult)NSOrderedDescending;
}else if (m.row > n.row){
return (NSComparisonResult)NSOrderedAscending;
} else {
return (NSComparisonResult)NSOrderedSame;
}
};

return [self sortedArrayUsingComparator:descendingSort];
}
@end
在进行网络删除的时候,如果要传递Id过去,则需要将选中元素的id取出,放到数组中,如何将NSInteger的值存入数组呢,使用NSNumber包裹下存入即可。

----------------------------------11.10------------------------------------------

29.在ARC环境下使用Block作为属性(@property)时候该怎么声明呢,使用如下形式实现均可。

@property (nonatomic, copy) void (^simpleCompletionBlock)(void);
@property (copy)void (^doStuff)(void);
typedef void(^MyCustomBlock)(void);

@interface MyClass : NSObject

@property (nonatomic, copy) MyCustomBlock customBlock;

@end
以上三种均可:详见:Can I use Objective-C blocks as properties?、How
to store blocks in properties in Objective-C?

----------------------------------11.14------------------------------------------

30. OC 里面NSLog()一个int 类型的值,可以使用%d输出,附上其他常见输出格式。

%@ 对象
%d, %i 整数
%u   无符整形
%f 浮点/双字
%x, %X 二进制整数
%o 八进制整数
%zu size_t
%p 指针
%e   浮点/双字 (科学计算)
%g   浮点/双字
%s C 字符串
%.*s Pascal字符串
%c 字符
%C unichar
%lld 64位长整数(long long)
%llu   无符64位长整数
%Lf 64位双字
----------------------------------11.15------------------------------------------

31.scrollview 滚动到指定位置,tableview也一样。

[_scrollView setContentOffset:CGPointMake(kScreenWidth,0) animated:YES];

----------------------------------11.17------------------------------------------

32.设置UITextField内边距方法:

[remarktext setValue:[NSNumber numberWithInt:5] forKey:@"_paddingTop"];
[remarktext setValue:[NSNumber numberWithInt:5] forKey:@"_paddingLeft"];
[remarktext setValue:[NSNumber numberWithInt:5] forKey:@"_paddingBottom"];
[remarktext setValue:[NSNumber numberWithInt:5] forKey:@"_paddingRight"];
// 在ios7 以后,可能需要使用去掉_的方法,如下
[phoneNumField setValue:[NSNumber numberWithInt:5] forKey:@"paddingTop"];
[phoneNumField setValue:[NSNumber numberWithInt:5] forKey:@"paddingLeft"];
[phoneNumField setValue:[NSNumber numberWithInt:5] forKey:@"paddingBottom"];
[phoneNumField setValue:[NSNumber numberWithInt:5] forKey:@"paddingRight"];
设置UITextView 的方式可能更简单些:(注:也适用于其他一些控件如UIButton)

summaryField.contentInset = UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
(http://unmi.cc/uilable-uitextfield-padding-insets/)

----------------------------------11.21------------------------------------------

33.iOS设置斜体字,以textview为例:

self.textView.text = @"请输入相片简介……";
CGAffineTransform matrix =  CGAffineTransformMake(1, 0, tanf(15 * (CGFloat)M_PI / 180), 1, 0, 0);
NSString *fontName = kPhotoExtendBarNormalFont.fontName;
UIFontDescriptor *desc = [UIFontDescriptor fontDescriptorWithName:fontName
matrix:matrix];
self.textView.font = [UIFont fontWithDescriptor:desc size:16];
34.设置UIDatePicker范围

datePicker.maximumDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
datePicker.minimumDate = [NSDate getDateFromString: [dateFormatter dateFromString:@"1900-01-01"]];
设置成日期类型:

datePicker.datePickerMode = UIDatePickerModeDate;
----------------------------------11.24------------------------------------------

怎样判断iOS App是通过哪种途径启动的?

SQLite加密方式

iOS下微信语音播放之切换听筒和扬声器的方法解决方案[转]

ios 画图总结

发送邮件

发送短信

从图片中的一点取色

iPhone 利用CG API画一个饼图(Pie chart)

结合UIImageView实现图片的移动和缩放.

设置拉伸图像按钮样式

转码可以使用python python-->print(u'\u611f\u597d'.encode('utf8'))

如果你的程序中用到了WiFi,想在没有有效WiFi的时候出现如图所示的提示该怎么做?

其实很简单, 只需要在Info.plist中添加如下Key/Value UIRequiresPersistentWiFi true

----------------------------------11.25------------------------------------------

35.UICollection如果cell比较少的情况下会不能上下滑动,你要是添加刷新的时候则不能够执行,你只需要设置collectionView.alwaysBounceVertical = YES;
即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐