0

TNContainerはUIViewのサブクラス化されており、drawRectメソッドに対して次のようにしています

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationBar setBackgroundImage:[UIImage imageNamed: @"UINavigationBarBlackOpaqueBackground.png"]
                                       forBarMetrics:UIBarMetricsDefault];
    self.containerView      =   [[TNContainer alloc] initWithFrame:CGRectMake(0, 0, 100, 10)];
    self.navigationBar.topItem.titleView    =   self.containerView;

}

私の中TNContainer.mで、私はやっています(境界とフレームを出力するためにいくつかのステートメントを入れています)

#import "TNContainer.h"

@implementation TNContainer

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    NSLog(@"frame at initWithFrame is %@", NSStringFromCGRect(self.frame));
    NSLog(@"bound at initWithFrame is %@", NSStringFromCGRect(self.bounds));
    return self;
}

-(void) drawRect:(CGRect)rect{
    [super drawRect:rect];
    NSLog(@"frame at drawRect is %@", NSStringFromCGRect(self.frame));
    NSLog(@"bounds at drawRect is %@", NSStringFromCGRect(self.bounds));

    CGRect rectangle        = self.bounds;
    CGContextRef context    = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor orangeColor].CGColor);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillRect(context, rectangle);
}

initWithFrameとで枠の境界drawRectが全然違うのがとても面白い

2013-09-25 16:19:47.926 TNSegmentController[10458:a0b] frame at initWithFrame is {{0, 0}, {100, 10}}
2013-09-25 16:19:47.928 TNSegmentController[10458:a0b] bound at initWithFrame is {{0, 0}, {100, 10}}
2013-09-25 16:19:47.934 TNSegmentController[10458:a0b] frame at drawRect is {{110, 17}, {100, 10}}
2013-09-25 16:19:47.934 TNSegmentController[10458:a0b] bounds at drawRect is {{0, 0}, {100, 10}}

なぜ{{110, 17}, {100, 10}}フレームを取得しているのかdrawRect()....

これについてのアイデアはありますか?

4

2 に答える 2

2

それはまったく奇妙なことではありません - 実際、それは当然のことです。-initWithFrame:時には、 origin を持つフレームを渡し(0,0)ます。そのフレームは、UIView サブクラスに正式に記録されます。

ただし、そのビューが描画されるまでには、それをtitleViewナビゲーション バーの に割り当てています。バーはビューを独自のサブビューとして追加し、中央に配置するように再配置した可能性があります。あなたの最初の描画リクエストは、すべてのことが起こるまで来ません。それが、別のオリジンがオーバーライドに表示される理由(110,17)です-drawRect:

(元のサイズが保持されていることに気付くでしょう。これは、あなたが本当に気にかけていることだと思います。ビューの原点を変更すること、つまりフレームを変更することは、カスタムタイトルビューを使用するための望ましい動作です。)

于 2013-09-25T20:36:10.483 に答える