我创建了包含4个组件的UIPickerView
。
我可以为UIPickerView
中的每个组件添加标题标题吗?
感谢您的任何建议
答案 0 :(得分:6)
我不时使用的另一种技术是将标题作为每列中的第一行:
你需要增加行数..
答案 1 :(得分:6)
Swift 版本,基于@ greentor的答案并做了一些改进:
var labelTexts = ["Months", "Weeks", "Days", "Hours", "Minutes"]
override func viewDidAppear(animated: Bool) {
let labelWidth = itemPicker.frame.width / CGFloat(itemPicker.numberOfComponents)
for index in 0..<labelTexts.count {
let label: UILabel = UILabel.init(frame: CGRectMake(itemPicker.frame.origin.x + labelWidth * CGFloat(index), 0, labelWidth, 20))
label.text = labelTexts[index]
label.textAlignment = .Center
itemPicker.addSubview(label)
}
请注意,如果在ViewWillAppear或更早版本中调用此方法,则可能无法正常工作,因为UIPickerView尚未知道此时的帧尺寸。
答案 2 :(得分:4)
我展示了3个组件,然后使用UIView显示在每个组件上方居中的标题(UILabel)(您可以轻松地将其修改为更多或更少的组件):
-(void)labelForDays
{
NSString *strDay = @"Days";
float lblWidth = self.pickerDayHourMin.frame.size.width / self.pickerDayHourMin.numberOfComponents;
float lblXposition = self.pickerDayHourMin.frame.origin.x;
float lblYposition = (self.pickerDayHourMin.frame.origin.y);
UILabel *lblDay = [[UILabel alloc] initWithFrame:CGRectMake(lblXposition,
lblYposition,
lblWidth,
20)];
[lblDay setText:strDay];
[lblDay setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:lblDay];
}
然后是第二个组件的标签
-(void)labelForHours
{
NSString *strHours = @"Hours";
float lblWidth = self.pickerDayHourMin.frame.size.width / self.pickerDayHourMin.numberOfComponents;
float lblXposition = self.pickerDayHourMin.frame.origin.x;
float lblYposition = (self.pickerDayHourMin.frame.origin.y);
UILabel *lblHours;
if (self.pickerDayHourMin.numberOfComponents ==3)
{
lblHours = [[UILabel alloc] initWithFrame:CGRectMake((lblXposition + lblWidth),
lblYposition,
lblWidth,
20)];
}
[lblHours setText:strHours];
[lblHours setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:lblHours];
}
最后是一个位于第3个组件上方的标签
-(void)labelForMinutes
{
NSString *strMinute = @"Minutes";
float lblWidth = self.pickerDayHourMin.frame.size.width / self.pickerDayHourMin.numberOfComponents;
float lblXposition = self.pickerDayHourMin.frame.origin.x;
float lblYposition = (self.pickerDayHourMin.frame.origin.y);
UILabel *lblMinute;
if (self.pickerDayHourMin.numberOfComponents ==3)
{
lblMinute = [[UILabel alloc] initWithFrame:CGRectMake((lblXposition + lblWidth + lblWidth),
lblYposition,
lblWidth,
20)];
}
[lblMinute setText:strMinute];
[lblMinute setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:lblMinute];
}
答案 3 :(得分:3)
您可以在UIPicker视图上方使用UIlabel,效果很好