为什么我的UIActivityIndicator在UIButton中作为子视图进入负x坐标



中有以下代码
- (void) loadView {
    self.okButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    CGFloat w = 20;
    self.indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(5, 0, w, w)];
    indicator.hidesWhenStopped = YES;
    self.indicator.center = self.okButton.center;
    [self.okButton addSubview:indicator];
    indicator.autoresizingMask = UIViewAutoresizingNone;
}

okButton被添加到一个复杂的视图层次结构中。我希望指示器正确地放置在okButton。但是在loadview和viewDidLoad中,帧给出了以下值

<UIButton: 0x210620a0; frame = (10 121; 300 50); opaque = NO; autoresize = W; layer = <CALayer: 0x21061560>>, 
<UIActivityIndicatorView: 0x21062540; frame = (-0.5 15; 20 20); hidden = YES; layer = <CALayer: 0x21062640>>

为什么指标的x从5变为-0.5 ?

编辑:我应该删除一行,计算指示器的位置,如下所示

//    self.indicator.center = self.okButton.center;
CGFloat size = 20, y = (self.okButton.frame.size.height - size)/2;
self.indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(5, y, size, size)];

我想你的问题在这一行:

self.indicator.center = self.okButton.center;

指示器是okButton的子视图,但是您设置了与superview相关的x和y值的坐标。你应该使用width/2和height/2来获得视图内部的居中

最新更新