iOS开发小技巧(一)

改变UIImagePickerController的导航条以及title的颜色

1
2
3
4
5
6
7
8
9
10
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
UINavigationBar *bar = [UINavigationBar appearance];
NSMutableDictionary *titleDictionary = [NSMutableDictionary dictionary];
titleDictionary[NSForegroundColorAttributeName] = [UIColor whiteColor];
[bar setTitleTextAttributes:titleDictionary];
viewController.navigationController.navigationBar.barTintColor = DIF_BASE_COLOR;
viewController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

利用KVC改变TextField的占位符的颜色

1
[self.nickNameTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

TextView的字数限制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#define MaxNumberOfDescriptionChars  150

-(void)textViewEditChanged:(NSNotification *)obj{
UITextView *textView = (UITextView *)obj.object;
NSString *toBeString = textView.text;
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > MaxNumberOfDescriptionChars) {
textView.text = [toBeString substringToIndex:MaxNumberOfDescriptionChars];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else{
if (toBeString.length > MaxNumberOfDescriptionChars) {

textView.text = [toBeString substringToIndex:MaxNumberOfDescriptionChars];
}
}
}



- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSString *new = [textView.text stringByReplacingCharactersInRange:range withString:text];
self.numLabel.text = [NSString stringWithFormat:@"%zd字",(MaxNumberOfDescriptionChars - new.length)];
if(new.length > MaxNumberOfDescriptionChars){
self.numLabel.text = [NSString stringWithFormat:@"%zd字",0];
if (![text isEqualToString:@""]) {
return NO;
}
}
return YES;
}

判断字符串或者集合类型是否为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
+ (BOOL)isEmpty:(id )obj
{
if ([obj isKindOfClass:[NSString class]]) {
if(obj == nil || [obj class] == [NSNull null] || [obj isEqualToString:@""] || [obj isEqualToString:@"(null)"] || [obj isEqualToString:@"NULL"] || [obj isEqualToString:@"<null>"] || [obj isEqualToString:@"null"])
{
return YES;
}
return NO;
}
if (obj == nil || (NSNull *)obj == [NSNull null] || ([obj respondsToSelector:@selector(length)] && [obj length] == 0) || ([obj respondsToSelector:@selector(count)] && [obj count] == 0)){
return YES;
}
return NO;
}

给UIResponder添加indexPath属性

列如在cell中有button imageview 可以利用该属性找到cell中改该视图

objective - C

1
2
3
4
5
@interface UIResponder (Externtion)

@property (nonatomic, strong) NSIndexPath *indexPath;

@end
1
2
3
4
5
6
7
8
9
- (void)setIndexPath:(NSIndexPath *)indexPath
{
objc_setAssociatedObject(self, @selector(indexPath), indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (NSIndexPath *)indexPath{
return objc_getAssociatedObject(self, @selector(indexPath));
}

swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
extension UIResponder{

private struct AssociatedKey {
static var AssociatedName = "AssociatedName"
}


public var indexPath: NSIndexPath?{
get{
return objc_getAssociatedObject(self, &AssociatedKey.AssociatedName) as? NSIndexPath
}

set{
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKey.AssociatedName, newValue as NSIndexPath , .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}

UIRefreshControl

1
2
3
4
5
6
7
8
9
let refresh = UIRefreshControl.init()
refresh.tintColor = UIColor.red
refresh.attributedTitle = NSAttributedString.init(string: "正在加载")
refresh.addTarget(self, action: #selector(ViewController.refreshTabeleView(sender:)), for: UIControlEvents.valueChanged)


tableView.refreshControl = refresh
tableView.addSubview(refresh)
tableView.reloadData()

将HTML字符串转化为NSAttributedString富文本字符串

1
2
3
4
5
6
7
8
9
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };

NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];

return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}

CABasicAnimation(CAKeyframeAnimation)key path 取值

keyPath可以使用的key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
- define angle2Radian(angle) ((angle)/180.0*M_PI)

transform.rotation.x 围绕x轴翻转 参数:角度 angle2Radian(4)

transform.rotation.y 围绕y轴翻转 参数:同上

transform.rotation.z 围绕z轴翻转 参数:同上

transform.rotation 默认围绕z轴

transform.scale.x x方向缩放 参数:缩放比例 1.5

transform.scale.y y方向缩放 参数:同上

transform.scale.z z方向缩放 参数:同上

transform.scale 所有方向缩放 参数:同上

transform.translation.x x方向移动 参数:x轴上的坐标 100

transform.translation.y x方向移动 参数:y轴上的坐标

transform.translation.z x方向移动 参数:z轴上的坐标

transform.translation 移动 参数:移动到的点 (100,100)

opacity 透明度 参数:透明度 0.5

backgroundColor 背景颜色 参数:颜色 (id)[[UIColor redColor] CGColor]

cornerRadius 圆角 参数:圆角半径 5

borderWidth 边框宽度 参数:边框宽度 5

bounds 大小 参数:CGRect

contents 内容 参数:CGImage

contentsRect 可视内容 参数:CGRect 值是0~1之间的小数

hidden 是否隐藏

position

shadowColor

shadowOffset

shadowOpacity

shadowRadius

隐藏导航条和tabBar的直线

1
2
3
UINavigationBar *bar = [UINavigationBar appearance];
bar.shadowImage = [UIImage new];
[bar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
1
2
3
UITabBar *tabBar = [UITabBar appearance];
tabBar.shadowImage = [UIImage new];
tabBar.backgroundImage = [UIImage new];

全屏手势返回

1
2
3
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self.interactivePopGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];
pan.delegate = self;
[self.view addGestureRecognizer:pan];
1
2
3
4
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
return self.childViewControllers.count > 1;
}

UITextView的placeholder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (void)textViewDidBeginEditing:(UITextView *)textView {
[self resetTextViewPlaceholderWithText:textView];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
[self resetTextViewPlaceholderWithText:textView];
}

- (void)resetTextViewPlaceholderWithText:(UITextView *)textView
{
if ([textView.text isEqualToString:@"要显示的placeholder"]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
return;
}
if (textView.text.length < 1) {
textView.text = @"要显示的placeholder";
textView.textColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1.00];
return;
}
}

让应用支持摇一摇

  • 开启摇一摇权限
1
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
  • 让view/viewcontroller成为第一响应者
1
2
3
4
#pragma mark - UIResponder
- (BOOL)canBecomeFirstResponder {
return YES;
}
  • 实现方发
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#pragma mark - 摇动
/**
* 摇动开始
*/
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
// do some thing
}
}

/**
* 摇动结束
*/
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}

/**
* 摇动取消
*/
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}

HeaderView随tableview一起滑动

1
2
3
4
5
6
7
8
9
10
11
12
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == self.tableView) {

CGFloat headerHeight = DIF_SCREEN_HEIGHT / 3;
if (scrollView.contentOffset.y <= headerHeight && scrollView.contentOffset.y >= 0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
}else if (scrollView.contentOffset.y >= headerHeight){
scrollView.contentInset = UIEdgeInsetsMake(-headerHeight, 0, 0, 0);
}
}
}