首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何以编程方式向UITableViewCell添加竖线

如何以编程方式向UITableViewCell添加竖线
EN

Stack Overflow用户
提问于 2018-05-06 01:40:13
回答 1查看 234关注 0票数 0

我试图在UITableView中的每个项目旁边添加一个彩色竖条,但不确定实现这一目标的正确和最有效的方法。是否有可能重用相同的UITableViewCell来以不同的方式给条形图着色?由于项目D有3个垂直条,项目F和G有2个垂直彩色条,我需要创建不同的自定义UITableViewCell吗?是否可以使用而不是UIImageView?仅仅为了纯色而使用图像似乎是非常低效的。如何使用Swift 4.0以编程方式完成此操作?我已经看过这个了:

但这并不能解决问题。

我还希望满足以下条件:

项目A、B、C、E和H的宽度为20,UITableViewCell.

  • Item D的高度为20,
  1. UITableViewCell的高度为20。每个彩色垂直条的宽度为4,包括每个彩色垂直条之间的白色条。
  2. 项目F和G的宽度为20,高度为UITableViewCell。每条竖条颜色为8宽,中间留4条,背景颜色为白色。

视图控制器

代码语言:javascript
复制
import UIKit

class MyViewController: UIViewController {

    let cellId = "cellId"

    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView
    }()


    var allItems = ["Item A", "Item B", "Item C", "Item D", "Item E", "Item F", "Item G", "Item H"]


    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Hello World"

        self.tableView.register(CustomCell.self as AnyClass, forCellReuseIdentifier: "Cell")


        view.addSubview(tableView)

        let constraints = [
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ]

        NSLayoutConstraint.activate(constraints)
    }
}

extension MyViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell:CustomCell? = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? CustomCell

        if cell == nil {
            cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        }

        cell?.textLabel?.text = allItems[indexPath.row]

        return cell!
    }
}

自定义UITableViewCell

代码语言:javascript
复制
import Foundation
import UIKit

class CustomCell: UITableViewCell {
    enum BarStyle {
        case single
        case double
        case triple
    }

    var barStyle: BarStyle = .single {
        didSet {
            switch barStyle {
            case .single:
                bar.style = .single
            case .double:
                bar.style = .double
            case .triple:
                bar.style = .triple
            }
        }
    }
    var barColor = UIColor.black {
        didSet {
            bar.color = barColor
        }
    }

    private let bar = VerticalBarView(frame: .zero)

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        commonInit()
    }

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

        commonInit()
    }

    func commonInit() {
        self.contentView.addSubview(bar)
        // setup constraints as needed so bar is positioned and sized properly
        let constraints = [
            VerticalBarView.topAnchor.constraint(equalTo: CustomCell.topAnchor),
            VerticalBarView.bottomAnchor.constraint(equalTo: CustomCell.bottomAnchor)
        ]

        NSLayoutConstraint.activate(constraints)
    }
}

Plist文件(Items.plist)

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>name</key>
        <string>Item A</string>
        <key>style</key>
        <string>single</string>
        <key>colour</key>
        <string>A90F32</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item B</string>
        <key>style</key>
        <string>single</string>
        <key>colour</key>
        <string>427B7B</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item C</string>
        <key>style</key>
        <string>single</string>
        <key>colour</key>
        <string>C9910D</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item D</string>
        <key>single</key>
        <string>triple</string>
        <key>colour</key>
        <string>CF009E</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item E</string>
        <key>style</key>
        <string>single</string>
        <key>colour</key>
        <string>003CA6</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item F</string>
        <key>style</key>
        <string>double</string>
        <key>colour</key>
        <string>704B1C</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item G</string>
        <key>style</key>
        <string>double</string>
        <key>colour</key>
        <string>6EC4E8</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Item H</string>
        <key>style</key>
        <string>single</string>
        <key>colour</key>
        <string>95BF32</string>
    </dict>
</array>
</plist>

Extensions.swift

代码语言:javascript
复制
import Foundation
import UIKit

extension UIColor {

    static let colorRed = UIColor().colorFromHex("A90F32")
    static let colorTeal = UIColor().colorFromHex("427B7B")
    static let colorGold = UIColor().colorFromHex("C9910D")
    static let colorMagenta = UIColor().colorFromHex("CF009E")
    static let colorNavy = UIColor().colorFromHex("003CA6")
    static let colorBrown = UIColor().colorFromHex("704B1C")
    static let colorLightBlue = UIColor().colorFromHex("6EC4E8")
    static let colorGreen = UIColor().colorFromHex("95BF32")

    func colorFromHex(_ hex : String) -> UIColor {
        var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if hexString.hasPrefix("#") {
            hexString.remove(at: hexString.startIndex)
        }

        if hexString.count != 6 {
            return UIColor.black
        }

        var rgb : UInt32 = 0
        Scanner(string: hexString).scanHexInt32(&rgb)

        return UIColor.init(red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
                            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
                            blue: CGFloat(rgb & 0x0000FF) / 255.0,
                            alpha: 1.0)
    }
}

Items.swift (包含结构)

代码语言:javascript
复制
import Foundation    

struct mainItem {
    var title: String
    var style: String
    var color: String
}

var itemA = mainItem(title: "Item A", style: "single", color: "A90F32")
var itemB = mainItem(title: "Item B", style: "single", color: "427B7B")
var itemC = mainItem(title: "Item C", style: "single", color: "C9910D")
var itemD = mainItem(title: "Item D", style: "triple", color: "CF009E")
var itemE = mainItem(title: "Item E", style: "single", color: "003CA6")
var itemF = mainItem(title: "Item F", style: "double", color: "704B1C")
var itemG = mainItem(title: "Item G", style: "double", color: "6EC4E8")
var itemH = mainItem(title: "Item H", style: "single", color: "95BF32")

当前结果

预期结果

rmaddy的建议

EN

回答 1

Stack Overflow用户

发布于 2018-05-06 01:48:50

这里面有很多东西,所以把它分解一下吧。

首先,您需要一种创建垂直条的方法。您可以使用图像,但我建议您创建一个定义两个属性的自定义UIView:样式(实线、两条线、三条线)和颜色。定义样式的enum。实现draw根据需要绘制彩色条形图。

一旦该自定义视图正常工作,就可以实现CustomCell,以便在其contentView的左端添加该自定义视图的一个实例。将条形样式和颜色的属性添加到CustomCell类。设置这些属性应该会更新自定义条视图上的相应属性。

更新表视图控制器中的数据模型,以包括每行的颜色和样式。

更新cellForRowAt以设置CustomCell的标题、条形图样式和条形图颜色。

下面是实现条形图的一种方法:

代码语言:javascript
复制
class VerticalBarView: UIView {
    enum Style {
        case single
        case double
        case triple
    }

    var style: Style = .single {
        didSet {
            setNeedsDisplay()
        }
    }
    var color = UIColor.black {
        didSet {
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {
        (backgroundColor ?? .white).set()
        let bg = UIBezierPath(rect: bounds)
        bg.fill()

        color.set()

        switch style {
        case .single:
            let path = UIBezierPath(rect: bounds)
            path.fill()
        case .double:
            let left = CGRect(x: 0, y: 0, width: bounds.width / 2 - 2, height: bounds.height)
            var right = left
            right.origin.x = right.width + 4
            let pathLeft = UIBezierPath(rect: left)
            pathLeft.fill()
            let pathRight = UIBezierPath(rect: right)
            pathRight.fill()
        case .triple:
            let width = (bounds.width - 8) / 3
            var left: CGFloat = 0
            for _ in 0..<3 {
                let rect = CGRect(x: left, y: 0, width: width, height: bounds.height)
                let path = UIBezierPath(rect: rect)
                path.fill()
                left += width + 4
            }
        }
    }
}

// Test code
let view = VerticalBarView(frame: CGRect(x: 0, y: 0, width: 20, height: 44))
view.style = .triple
view.color = UIColor.purple

下面是CustomCell的粗略实现

代码语言:javascript
复制
class CustomCell: UITableViewCell {
    enum BarStyle {
        case single
        case double
        case triple
    }

    var barStyle: BarStyle = .single {
        didSet {
            switch barStyle {
            case .single:
                bar.style = .single
            case .double:
                bar.style = .double
            case .triple:
                bar.style = .triple
            }
        }
    }
    var barColor = UIColor.black {
        didSet {
            bar.color = barColor
        }
    }

    private let bar = VerticalBarView(frame: .zero)

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        commonInit()
    }

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

        commonInit()
    }

    func commonInit() {
        self.contentView.addSubview(bar)

        let constraints = [
            bar.topAnchor.constraint(equalTo: self.contentView.topAnchor),
            bar.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
            bar.leftAnchor.constraint(equalTo: self.contentView.leftAnchor),
            bar.widthAnchor.constraint(equalToConstant: 20)
        ]
        NSLayoutConstraint.activate(constraints)
    }
}

您的cellForRowAt如下所示:

代码语言:javascript
复制
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell

    cell.textLabel?.text = allItems[indexPath.row].title
    cell.barStyle = allItems[indexPath.row].style
    cell.barColor = allItems[indexPath.row].color

    return cell
}

这最后一段代码假设您已经将数据模型更新为一个结构数组,其中结构包含标题、样式和颜色。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50192321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档