【问题标题】:Gradient background iPhone dimensions on iPadiPad 上的渐变背景 iPhone 尺寸
【发布时间】:2019-10-02 08:29:27
【问题描述】:

我在 iPad 上设置渐变背景时遇到问题。在 iPhone 上一切正常,但当我使用 iPad 时,渐变背景具有 iPhone 尺寸。

我用来制作渐变的代码如下。

func setGradientToTableView(tableView: UITableView) {

        let gradientBackgroundColors = [UIColor(red: 190.0/255.0, green: 219.0/255.0, blue: 0.0/255.0, alpha: 1).cgColor, UIColor(red: 13.0/255.0, green: 227.0/255.0, blue: 97.0/255.0, alpha: 1).cgColor]

        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientBackgroundColors
        gradientLayer.startPoint = CGPoint(x: 0,y: 0)

        gradientLayer.frame = tableView.bounds
        let backgroundView = UIView(frame: tableView.bounds)
        backgroundView.layer.insertSublayer(gradientLayer, at: 0)
        tableView.backgroundView = backgroundView
    }

【问题讨论】:

  • 你在哪里打电话setGradientToTableView()
  • @MumtazHussain 在viewDidLoad()。我对自定义视图也有同样的问题。总是在左上角。

标签: ios swift xcode ios-simulator


【解决方案1】:

您需要在viewDidLayoutSubviews中为图层设置框架:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.backgroundView?.layer.sublayers?.forEach { $0.frame = tableView.bounds }
    }

此外,正如@Jan Schlorf 在评论中建议的那样,您可以将图层存储为属性:

    lazy var gradientLayer = CAGradientLayer()

    //...

    func setGradientToTableView(tableView: UITableView) {
        let gradientBackgroundColors = [UIColor(red: 190.0/255.0, green: 219.0/255.0, blue: 0.0/255.0, alpha: 1).cgColor, UIColor(red: 13.0/255.0, green: 227.0/255.0, blue: 97.0/255.0, alpha: 1).cgColor]

        gradientLayer.colors = gradientBackgroundColors
        gradientLayer.startPoint = CGPoint(x: 0,y: 0)

        gradientLayer.frame = tableView.bounds
        let backgroundView = UIView(frame: tableView.bounds)
        backgroundView.layer.insertSublayer(gradientLayer, at: 0)
        tableView.backgroundView = backgroundView
    }

    //...

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        gradientLayer.frame = tableView.bounds
    }

【讨论】:

  • 提出改进建议;我会将gradientLayer 存储在一个属性中,并且只更改它的框架,因为您的代码可能会调整大小而不仅仅是gradientLayer
【解决方案2】:

我假设你没有使用自动布局?

在使用 iPad Simulator 启动应用时检查您的 tableviewsize。我认为它没有你想象的那么大。

【讨论】:

  • 我使用了自动布局。查看单元格大小。
猜你喜欢
  • 2013-01-01
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多