Objective c uipickerview中带有约束的uilabel自定义定位
我希望在UIPickerView中有自定义UILabel,它右对齐,宽度=屏幕宽度的一半: 如何使用NSConstraints定位所有内容?我有一些问题,因为当我有机会修改它时,UILabel并没有附加到super view 我设法让它工作,但它没有与NSConstraints一起完成,可能是错误的(如果我将UILabel嵌入到另一个视图中,我就能够设置框架)。有什么建议如何正确地做吗Objective c uipickerview中带有约束的uilabel自定义定位,objective-c,autolayout,Objective C,Autolayout,我希望在UIPickerView中有自定义UILabel,它右对齐,宽度=屏幕宽度的一半: 如何使用NSConstraints定位所有内容?我有一些问题,因为当我有机会修改它时,UILabel并没有附加到super view 我设法让它工作,但它没有与NSConstraints一起完成,可能是错误的(如果我将UILabel嵌入到另一个视图中,我就能够设置框架)。有什么建议如何正确地做吗 - (UIView *)pickerView:(UIPickerView *)pickerView view
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
CGFloat width = [UIScreen mainScreen].bounds.size.width;
UIView * newView = [[UIView alloc] init];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0.0f, width / 2 + 18, [pickerView rowSizeForComponent:component].height)];
lbl.text = [self.datasource objectAtIndex:row];
lbl.textAlignment = NSTextAlignmentRight;
lbl.font=[UIFont CPGeneralFontWithSize:22];
[newView addSubview:lbl];
return newView;
}
我认为你添加标签的方式没有任何问题。默认情况下,viewForRow:forComponent:返回的视图与选择器视图的宽度相同,因此添加标签作为子视图是获得所需外观的正确方法。如果要使用约束添加标签,可以这样做
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UIView * newView = [[UIView alloc] init];
UILabel *lbl = [[UILabel alloc] init];
lbl.translatesAutoresizingMaskIntoConstraints = NO;
lbl.backgroundColor = [UIColor redColor];
lbl.text = self.datasource[row];
lbl.textAlignment = NSTextAlignmentRight;
lbl.font=[UIFont PGeneralFontWithSize:22];
[newView addSubview:lbl];
[newView addConstraint:[NSLayoutConstraint constraintWithItem:lbl attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:newView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
[newView addConstraint:[NSLayoutConstraint constraintWithItem:lbl attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:newView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0]];
[newView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[lbl]|" options:0 metrics:nil views:@{@"lbl":lbl}]];
return newView;
}
我不确定这一点,但我记得我已经在这里读过了,所以你需要用标签和对齐/填充来作弊。所谓欺骗,我的意思是增加不可见区域,使它移动到你想要的地方。你说的“不可见区域”是什么意思?添加更多组件?是否在label.text中添加额外的空格?