UIView *indicateView = [[UIView alloc]initWithFrame:CGRectMake(0, 33, 20, 2)]; indicateView.backgroundColor = [UIColor redColor]; self.indicatorView = indicateView; //子选项 CGFloat width = self.view.width / 5; for (int i = 0; i < self.titles.count; i++) { UIButton *tap = [UIButton buttonWithType:UIButtonTypeCustom]; tap.tag = i; tap.backgroundColor = kRandomColor; tap.frame = CGRectMake(i * width, 0, width, 35); [tap setTitle:self.titles[i] forState:UIControlStateNormal]; [tap setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; [tap addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside]; [titleView addSubview:tap]; if (i == 0) { tap.titleLabel.backgroundColor = [UIColor yellowColor]; //[tap.titleLabel sizeToFit]; //[tap layoutIfNeeded]; NSLog(@"%f,%f",tap.titleLabel.width,tap.centerX); self.indicatorView.width = tap.titleLabel.width; //原因在这句,此时tap.titleLabel.width = 0,所以要强制布局,用sizeToFit或layoutIfNeeded self.indicatorView.centerX = tap.centerX; } }
控件创建出来设置了frame,在某处用了该控件的尺寸,但是系统也许在这个时候还没有计算该控件的尺寸什么的,所以这个时候就要强制系统计算布局。