Swift - 水平 UIPickerView
Posted
技术标签:
【中文标题】Swift - 水平 UIPickerView【英文标题】:Swift - Horizontal UIPickerView 【发布时间】:2020-05-01 18:14:11 【问题描述】:我正在尝试通过旋转 UIPickerView 然后旋转其中的标签来使用 Swift 制作一个水平选择器,我还尝试旋转其中的视图,而不是标签。
但是在这两种方法中,我得到的结果与图片中显示的相同,选择器内的标签仍未按预期显示。
请看照片和代码, 有关如何解决此问题的任何想法?
@IBOutlet weak var myPicker: UIPickerView!
var rotationAngle: CGFloat!
var pickerArray: [String] = [String]()
override func viewDidLoad()
super.viewDidLoad()
rotationAngle = -90 * (.pi/180)
myPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)
self.myPicker.delegate = self
self.myPicker.dataSource = self
pickerArray = ["Hello", "World", "What", "Where", "When", "How", "Hey", "Welcome", "Good", "Ok", "Bye", "World!"]
rotatePickerView(pickerView: myPicker)
func numberOfComponents(in pickerView: UIPickerView) -> Int
return 1
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return pickerArray.count
internal func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
return pickerArray[row]
func rotatePickerView(pickerView : UIPickerView)
myPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)
myPicker.frame = CGRect(x: -150, y: myPicker.frame.origin.y, width: view.frame.width + 300, height: 200)
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
let label = UILabel()
label.font = UIFont(name: "Helvetica", size: 24)
label.font = UIFont.systemFont(ofSize: 24, weight: .regular)
label.minimumScaleFactor = 0.5
label.textAlignment = .center
label.textColor = UIColor.black
label.transform = CGAffineTransform(rotationAngle: 90 * (.pi / 180 ))
label.text = pickerArray[row]
return label
【问题讨论】:
通过减小字体大小来检查 这不是字体大小问题。 【参考方案1】:您没有为标签指定框架,即它的宽度和高度。 初始化时需要指定label的frame,通过delegate函数指定view的高度。
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
let pickerRow = UIView()
pickerRow.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let rowLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
rowLabel.textColor = .black
rowLabel.text = yourData[row]
rowLabel.textAlignment = .center
pickerRow.addSubview(rowLabel)
pickerRow.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180))
return pickerRow
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
return 100
【讨论】:
以上是关于Swift - 水平 UIPickerView的主要内容,如果未能解决你的问题,请参考以下文章
在 UITableviewcell swift 中设置水平渐变
Swift 中一个垂直 ScrollView 中的多个水平 ScrollView?
如何使用 Swift 制作水平 UICollectionView