プロパティが変更したらそれをKVOで検知する方法
監視オブジェクトの追加
[self addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:NULL];
監視オブジェクトの受信
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"keyPath=%@\nobject=%@\nchange=%@\ncontext=%@", keyPath, object, change, context); }
こんな感じで出力される。便利〜。
keyPath=frame object=<LQAInquiryButtonView: 0x11931cd80; frame = (0 0; 320 94); autoresize = W+H; layer = <CALayer: 0x11935f270>> change={ kind = 1; new = "NSRect: {{0, 0}, {320, 94}}"; old = "NSRect: {{0, 0}, {320, 50}}"; } context=(null)
ビューが勝手にリサイズするのを防ぎたい
self.view.autoresizingMask = UIViewAutoresizingNone;
CocoaLumberjack を使ってログ機能を使いやすくする
#import "DDLog.h" #import "DDTTYLogger.h" #ifdef DEBUG static const int ddLogLevel = LOG_LEVEL_VERBOSE; #else static const int ddLogLevel = LOG_LEVEL_OFF; #endif
URLだけわかっていて画像を表示したい
SDWebImage の downloadWithURL:options:progress:completed: を使う。
[[SDWebImageManager sharedManager] downloadWithURL:imageURL options:SDWebImageHighPriority progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { if (error) { [Bugsnag notify:[NSException exceptionWithName:@"Download Image Exception" reason:error.localizedDescription userInfo:nil]]; } else if (finished) { self.contentTextView.image = image; } }];
テーブルビューのセル毎にピッタリの高さを計算する
高さが固定じゃなく、セルの内容毎に高さが変わる場合がありますよね。
そういう場合には Auto Layout で上下の Constraints を指定しつつ、systemLayoutSizeFittingSize: メソッドを使うと簡単に高さが取得出来ました(ちょっと処理が重い?)。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { static CustomTableViewCell *sizingCell; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil]; sizingCell = [[nib instantiateWithOwner:nil options:nil] firstObject]; }); sizingCell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(sizingCell.bounds)); sizingCell.stock = self.stocks[indexPath.row]; [sizingCell setNeedsLayout]; [sizingCell layoutIfNeeded]; CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; return size.height; }
UIScrollView に余白(マージンみたいなもの)を設定する
UITableView でも UIScrollView でも同じように設定できるっぽい。
scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 50.0f, 0); scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, 50.0f, 0);
文字列が空かどうかの判定
こんなカテゴリを用意しておくと楽かも。
- (BOOL)lxx_empty { return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0); }