iOSアプリ開発のメモ置き場

ささたつがiOSアプリ開発で知ったObjective-Cのtipsなどを書いていく所存

プロパティが変更したらそれを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)


参考:Key-value observingを使う際のtips

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;
}

参考:UITableViewCellの高さを動的に変えるサンプル

UIScrollView に余白(マージンみたいなもの)を設定する

UITableView でも UIScrollView でも同じように設定できるっぽい。

scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 50.0f, 0);
scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, 50.0f, 0);

参考:UIScrollViewに余白を設定する