【问题标题】:How can I set UITableView's section's header gradient (and transparent) background in Xcode?如何在 Xcode 中设置 UITableView 部分标题渐变(和透明)背景?
【发布时间】:2020-02-12 21:51:44
【问题描述】:

我尝试了多种方法,但不幸的是我无法成功。迄今为止最好的是comment

我认为解决方案应该在函数func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 中,但我不知道该怎么做。

我想得到类似this 的东西。我使用 Swift 5+,目标 iOS 可以是任何东西 (13+)。

【问题讨论】:

    标签: ios swift xcode uitableview


    【解决方案1】:

    1.使用 ViewForHeaderInSection 如下:

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = self.getGradientBackgroundView()
    
        // Add any title to the Header if needed
        let label = UILabel()
        label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
        label.text = "My header"
        headerView.addSubview(label)
    
        return headerView
    }
    

    2。使用 heightForHeaderInSection 设置标题的高度:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 50 //whatever height you needed.
        }
    

    3.获取渐变 BG Header View

      private func getGradientBackgroundView() -> UIView {
        let gradientBackgroundView = UIView()
    
        // Prepare Gradient Layer
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame.size = CGSize(width: self.myTableView.frame.size.width, height: 50) // height same as in heightForHeaderInSection
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
        // Add layer to view
        gradientBackgroundView.layer.addSublayer(gradientLayer)
        return gradientBackgroundView
      }
    

    希望这会有所帮助!!

    【讨论】:

    • 不幸的是,在我添加了这段代码之后,整个 tableView 变成了这种绿色。
    • 您必须根据您的需要在下面的行中更改颜色:gradientLayer.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
    • 此时颜色无关紧要。这是我看到的:prnt.sc/r1xpyv。这是在整个 tableview 中(如您所见,我滚动大约到 tableview 的一半以确保我看不到任何单元格)。
    • 我无法加载该页面,您可以将其附加到此处以方便查看吗?
    • @jasond - 哎呀,大小不正确!!!!检查我更新的答案,刚刚修改了 gradientLayer.frame.size 值。检查并告诉我
    猜你喜欢
    • 2015-05-03
    • 2016-09-25
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多