Swift:使用drawRect自定义UIView子视图

时间:2015-09-22 01:43:25

标签: ios swift

UITableViewCell的背景下实现自定义绘图的最佳方法是什么?

到目前为止,我已确定最有可能将自定义UIView子视图添加到单元格的内容视图中。

问题是滚动时单元格会不经意地重新绘制。

TestViewController:

import UIKit

class TestViewController: UIViewController {
    @IBOutlet weak var ListTableView: UITableView!

    ...

    override func viewDidLoad() {
    super.viewDidLoad()

    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("customcell", forIndexPath: indexPath)
        cell.textLabel?.text = items[indexPath.item].name
        return cell
    }
}

CustomUIView:

import UIKit

@IBDesignable

class ColoredUIView: UIView {

    @IBInspectable var barColor: UIColor = UIColor.greenColor()

    override func drawRect(rect: CGRect) {
        let barThickness: CGFloat = 3.0
        let barLeft: CGFloat = 5.0

        //Vertical Line
        let barPath = UIBezierPath()
        barPath.lineWidth = barThickness

        //move to the start of the vertical stroke
        barPath.moveToPoint(CGPoint(
            x:barLeft,
            y:0))

        //add the end point to the vertical stroke
        barPath.addLineToPoint(CGPoint(
            x:barLeft,
            y:bounds.height))

        //set the stroke color
        barColor.setStroke()

        //draw the stroke
        barPath.stroke()
    }
}

0 个答案:

没有答案