Last active
August 8, 2021 00:44
-
-
Save rijieli/38903d55d18db90e3b94824be97b7378 to your computer and use it in GitHub Desktop.
iOS Horizontal Picker View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HorizontalPickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate { | |
let types = ["不循环","每天","每周","每月","每年"] | |
let sliderControl: UIPickerView = { | |
let view = UIPickerView() | |
view.transform = CGAffineTransform(rotationAngle: -90 * (.pi / 180)) | |
return view | |
}() | |
init() { | |
super.init(frame: .zero) | |
sliderControl.dataSource = self | |
sliderControl.delegate = self | |
sliderControl.backgroundColor = .white | |
self.addSubview(sliderControl) | |
sliderControl.layoutSize(width: 28, height: 200).layoutAxis(self, x:0, y:0).layoutApply() | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
func numberOfComponents(in pickerView: UIPickerView) -> Int { | |
1 | |
} | |
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { | |
types.count | |
} | |
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { | |
// PickerView has n * UIPickerColumnView | |
// UIPickerColumnView has 3 child view, and last one is real view for row | |
// The code **hack** the last item | |
// pickerView.subviews[0].subviews.first?.subviews.last?.clipsToBounds = false | |
pickerView.subviews[1].isHidden = true | |
var pickerLabel : UILabel | |
if let label = view as? UILabel { | |
pickerLabel = label | |
} else { | |
pickerLabel = UILabel() | |
pickerLabel.font = .systemFont(ofSize: 14, weight: .medium) | |
pickerLabel.textColor = .black | |
pickerLabel.textAlignment = NSTextAlignment.center | |
pickerLabel.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180)) | |
} | |
pickerLabel.text = types[row] | |
pickerLabel.sizeToFit() | |
return pickerLabel | |
} | |
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { | |
80 | |
} | |
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { | |
return 28 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment