我正在尝试创建看起来像聊天项目的自定义单元格。
面临的挑战是:在上角添加三角形,并为聊天项设置共同的边框和阴影?
所有“云”的宽度相同。
最好的方法是什么?
最佳答案
我有个主意:
创建UIView的子类Triangle以绘制“ cloud”的“ 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
关于ios - 带有上角,边框和阴影的聊天项目 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42803594/