聊天项目视图与顶角,边框和阴影

时间:2017-03-15 07:36:09

标签: ios objective-c swift uitableview

我正在尝试创建看起来像聊天项的自定义单元格。 挑战是:在顶角添加三角形并制作聊天项的共同边框和阴影?

所有"云的宽度"是一样的。

实现它的最佳方法是什么?

enter image description here

1 个答案:

答案 0 :(得分:0)

我有个主意:

创建 UIView 的子类三角形以绘制" tail " " ":

class LeftTriangleView: UIView {

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

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.beginPath()
        context.move(to: CGPoint(x: rect.minX, y: rect.minY))
        context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        context.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        context.closePath()

        context.setFillColor(UIColor.gray.cgColor)
        context.fillPath()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



class RightTriangleView: UIView {

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

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.beginPath()
        context.move(to: CGPoint(x: rect.minX, y: rect.maxY))
        context.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
        context.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        context.closePath()


        context.setFillColor(UIColor.blue.cgColor)
        context.fillPath()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

<强>用法:

let leftTailView: LeftTriangleView = {
        let tail = LeftTriangleView()
        tail.backgroundColor = .white
        tail.isHidden = true

        return tail
    }()

let rightTailView: RightTriangleView = {
        let tail = RightTriangleView()
        tail.backgroundColor = .white
        tail.isHidden = true

        return tail
    }()

let cloudView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.95, alpha: 1)
        view.layer.cornerRadius = 5
        view.layer.masksToBounds = true

        return view
    }()



addSubview(cloudView)
addSubview(leftTailView)
addSubview(rightTailView)



leftTailView.anchor(topAnchor, left: nil, bottom: nil, right: bubbleView.leftAnchor, topConstant: 5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 9, heightConstant: 6)

rightTailView.anchor(topAnchor, left: bubbleView.rightAnchor, bottom: nil, right: nil, topConstant: 5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 9, heightConstant: 6)



If send message: 

rightTailView.isHidden = false


If received message: 

leftTailView.isHidden = false