当我在 iOS 中切换语言 RTL 时,UIPickerView 文本未居中对齐

UIPickerView text is not center aligned when I switch language RTL in iOS

我正在使用委托方法设置 UIPickerView 的标题并设置 .center 对齐方式。但如果我从英语切换到阿拉伯语,它就会右对齐。如果启动时语言为阿拉伯语,切换为英语后左对齐。

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let title = getPickerViewTitle(for: row)
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 37))
    label.text = title
    label.textAlignment = .center
    label.backgroundColor = UIColor.clear
    return label
}

无需尝试 UI 标签框架。只给你的选择器约束。

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView
{
    var pickerLabel = UILabel()
    pickerLabel.textColor = UIColor.blackColor()
    pickerLabel.text = "PickerView Cell Title"
    pickerLabel.font = UIFont.boldSystemFont(ofSize: 13)
    pickerLabel.textAlignment = NSTextAlignment.Center
    return pickerLabel
}

如果您在组件中使用 RTL 语言支持,那么您需要强制更新对齐。

 func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
            var pickerLabel : UILabel
            if let label = view as? UILabel {
                pickerLabel = label
            } else {
                pickerLabel = UILabel()
                pickerLabel.textColor = UIColor.black
                if  pickerLabel.effectiveUserInterfaceLayoutDirection == .rightToLeft {
                    pickerLabel.textAlignment = NSTextAlignment.center

                }
            }
            pickerLabel.text = "10"
            pickerLabel.sizeToFit()

            return pickerLabel
        }