gpt4 book ai didi

objective-c - uipickerview 中带有约束的 uilabel 自定义定位

转载 作者:搜寻专家 更新时间:2023-10-30 20:05:21 25 4
gpt4 key购买 nike

我想在 UIPickerView 中使用自定义 UILabel,它右对齐并且宽度 = 屏幕宽度的一半:

enter image description here

如何使用 NSConstraints 定位所有内容?我遇到了一些问题,因为当我有机会修改它时,UILabel 没有附加到 super View 。

我设法让它工作,但它没有用 NSConstraints 完成,并且可能是错误的(如果我将 UILabel 嵌入另一个 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: 返回的 View 与选择器 View 的宽度相同,因此将标签添加为 subview 是获得所需外观的正确方法。如果你想使用约束添加标签,你可以这样做,

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

关于objective-c - uipickerview 中带有约束的 uilabel 自定义定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com