ios开发中的小技巧

样式技巧


  • 设置状态栏样式(ios7之前是Application类中设置的,ios9后是在控制器中设置)
- (UIStatusBarStyle)preferredStatusBarStyle{    return UIStatusBarStyleLightContent;}
  • 设置UITextField光标颜色

    • $textField.tintColor = [UIColor $color];
  • 设置带颜色的文字 (NSAttributedString)

    • 很多控件都可以用它,例如:UITextField UILabel ....
//例1://可以用来设置某些可以使用attributedString作为文本的控件 使该文本拥有各种属性(富文本)
self.attributedPlaceholder = [[NSAttributedString alloc]                                 
                  initWithString:self.placeholder 
                  attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
//例:2
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"hello\n你好"];    
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, 2)];    
[text addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:22] range:NSMakeRange(3, 4)];    
UILabel *label = [[UILabel alloc] init];    
label.attributedText = text;    
label.numberOfLines = 0;    
[label sizeToFit];    
self.navigationItem.titleView = label;
ios开发中的小技巧_第1张图片
例2图片
  • 枚举类|符号串连值

所有>>位进符号的枚举值都可以使用|进行串连
x1|x2得到的值 & x1(或者x2)都会返回正数(次方) 反之亦然

 UIControlEventEditingDidBegin                                   = 1 << 16,     // UITextField
    UIControlEventEditingChanged                                    = 1 << 17,
    UIControlEventEditingDidEnd                                     = 1 << 18,
    UIControlEventEditingDidEndOnExit                               = 1 << 19,
  //UIControlEventEditingDidBegin | UIControlEventEditingChanged表示同时监听两个事件    
[self addTarget:self action:@selector(update) forControlEvents:UIControlEventEditingDidBegin | UIControlEventEditingChanged]
int a = 1 << 0;    
int b = 1 << 1;    
int c = 1 << 2;    
int value = a | b | c;    
NSLog(@"%i",value & a); //1    
NSLog(@"%i",value & b); //2    
NSLog(@"%i",value & c); //0
  • NSNotificationCenter监听通知
/*
表示当接受到名为`UITextFieldTextDidBeginEditingNotification`
的通知并且发送通知者是当前对象时,
调用自己的testNotification方法
*/
[[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(testNotification)
name:UITextFieldTextDidBeginEditingNotification object:self];
//类销毁后一定要移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//添加监听通知在其他线程执行 (注意,在其他线程无法刷新UI)
[[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidBeginEditingNotification object:self queue:[[NSOperationQueue alloc]init ]usingBlock:^(NSNotification * _Nonnull note) {
        NSLog(@"%@",[NSThread currentThread]);
        
    }];

你可能感兴趣的:(ios开发中的小技巧)