我正在尝试制作一个水平的UIPickerView。但我的宽度有问题。正如你可以在图像的顶部看到
我希望PickerView的宽度为= view.frame.size.width,但由于某种原因它保持非常小。在我的代码中我有:
let cityPicker = UIPickerView()
var rotationAngle: CGFloat!
let width:CGFloat = 100
let height:CGFloat = 100
override func viewDidLoad() {
super.viewDidLoad()
cityPicker.delegate = self
cityPicker.dataSource = self
cityPicker.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
self.view.addSubview(cityPicker)
rotationAngle = -90 * (.pi/180)
cityPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return byer.count
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 100
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 100
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: width, height: height)
let label = UILabel()
label.frame = CGRect(x: 0, y: 0, width: width, height: height)
label.textAlignment = .center
label.font = UIFont (name: "Baskerville-Bold", size: 30)
label.text = byer[row]
view.addSubview(label)
view.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180))
return view
}
谁能看到我做错了什么?
您应该只使用autolayout,但如果您想要手动布局,则无法在viewDidLoad
中使用视图的框架。此时,框架将与storyboard或nib文件中的框架相同,并且不会反映实际的设备或视图层次结构。您应该将您的手动调整逻辑放在viewDidLayoutSubviews
中。调用此函数时,视图的大小正确,您可以使用它来设置子视图。
var rotationAngle : CGFloat!
在您的ViewDidLoad中
rotationAngle = -90 * (.pi / 180 )
在你的班级写这个功能
func rotatePickerView(pickerView : UIPickerView) {
let y = pickerView.frame.origin.y
let x = pickerView.frame.origin.x
pickerView.transform = CGAffineTransform(rotationAngle: rotationAngle)
pickerView.frame = CGRect(x: x, y: y, width: pickerView.frame.height , height: pickerView.frame.width)
}
我们还需要在我们旋转pickerview时旋转标签,现在在viewForRow方法中。 (这些是Pickerview委托方法。)
let label = UILabel()
label.font = UIFont(name: "Helvetica", size: 40)
label.font = UIFont.systemFont(ofSize: 40, weight: .bold)
label.minimumScaleFactor = 0.5
label.textAlignment = .center
label.textColor = UIColor.white
label.transform = CGAffineTransform(rotationAngle: 90 * (.pi / 180 ))
//Put your values in an array like Minutes,Temperature etc.
label.text = minutes[row]
return label
在viewDidLoad中调用rotatePickerView函数并将pickerview作为参数输入,完成,谢谢;)