ios - UIPickerView 中 UIVIew 的背景颜色设置不正确

标签 ios iphone swift uipickerview picker

我正在尝试使用自定义设计实现 UIPickerView。我在 UIPickerView 中使用了一个 UIVIew,在我的 UIVIew 中使用了一个标签。我的选择器背景颜色是黑色,现在我正在尝试将白色背景颜色应用于 UIVIew 并在 View 中添加标签。但是颜色不是我想要的。我想要纯白色,但它正在返回灰色。谁能帮我解决这个问题?

这是我的代码和输出:

if pickerView == pkr1 {
    let myView = UIView(frame: CGRect(x: 5, y: 0, width: pickerView.bounds.width - 10, height: Utilities.isDeviceiPad() ? 80.0 : 60.0))
    myView.backgroundColor = UIColor.white
    myView.isOpaque = false
    let myLabel = UILabel(frame: CGRect(x: 5, y: 0, width: myView.bounds.width - 10, height: myView.frame.height))
    myLabel.text = arrTemp[row]
    //  myLabel.center.y = myView.center.y
    myLabel.textAlignment = .center
    myLabel.numberOfLines = 2
    myLabel.backgroundColor = UIColor.white
    myLabel.alpha = CGFloat(1)
    myLabel.lineBreakMode = NSLineBreakMode.byTruncatingTail

    myView.addSubview(myLabel)
    return myView
}

enter image description here

输出:

enter image description here

最佳答案

选中 View 透明的原因是UIPickerView subview ,它容纳了所有的内容,使用CAGradientLayer作为 mask 来实现深度效果。出于某种原因,Apple 决定也将所选 View 设为透明。我们不能简单地去掉那个面具,因为我们会失去那种奇特的效果。因此,我们需要进一步了解该梯度。

这是这个渐变的样子。我添加了 alpha channel 值,以便您可以看到此渐变的行为方式。

UIPickerView gradient layer mask

如您所见,它有 6 种颜色,除了中间的两个值外,一切都很好。它们是 0.8 而不是 1.0,这使您选择的 View 透明。

这是一个非常糟糕的方法,我强烈不建议这样做但是如果无论如何你都需要让你选择的项目不透明,你可以简单地创建一个你的子类 UIPickerView 并像那样更改渐变。

class MyPickerView: UIPickerView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.changeGradientLayer()
    }

    func changeGradientLayer() {
        guard let sublayers = self.subviews.first?.layer.sublayers else { return }

        for case let sublayer as CAGradientLayer in sublayers {
            sublayer.colors = [UIColor.black.withAlphaComponent(0).cgColor,
                               UIColor.black.withAlphaComponent(0.71).cgColor,
                               UIColor.black.withAlphaComponent(1.0).cgColor,
                               UIColor.black.withAlphaComponent(1.0).cgColor,
                               UIColor.black.withAlphaComponent(0.71).cgColor,
                               UIColor.black.withAlphaComponent(0).cgColor]
        }
    }

}

希望对你有帮助。

关于ios - UIPickerView 中 UIVIew 的背景颜色设置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52255908/

相关文章:

ios - 通过硬件获取 iPad 版本 - 哪个字符串适用于 iPad Air/mini?

iphone - 如何在 iOS 中求解条件方程

ios - 使用 AutoLayout 在 UIScrollView 底部查看

ios - 我无法通过 class_copyPropertyList 使用 swift 获取类的属性

android - Google Cloud Messaging 上的最大主题数

ios - 如何注册应用程序来开设地点

iphone - 在没有 managedObjectContext 的 View 之间传递 CoreData 对象

iphone - 第一个iPhone应用程序由于未知原因而崩溃

iphone - 如何在 iOS 的 UIWebView 上添加 Highcharts?

ios - 球体上的快速视频,黑屏但可以听到音频