更改UIButton矩形不带drawRect
问题描述:
我在xib上有一个UIButton,它是一个矩形,我想更改它的框架使其具有像角的箭头,但将其保留在xib(来自界面构建器),我该怎么做?更改UIButton矩形不带drawRect
我知道我可以使用drawRect中的UIBezierPath来做到这点,但那只是创建一个自定义形状并从代码中添加它。
还有别的办法吗?
class ButtonContinue: UIButton {
var path: UIBezierPath!
override func awakeFromNib() {
backgroundColor = UIColor.green
addTarget(self, action: #selector(touchDown), for: .touchDown)
}
override func draw(_ rect: CGRect) {
path = UIBezierPath()
path.move(to: CGPoint(x: 32, y: 28 + (rect.size.height/2)))
path.addLine(to: CGPoint(x: 70, y: 28))
path.addLine(to: CGPoint(x: rect.size.width, y: 28))
path.addLine(to: CGPoint(x: rect.size.width, y: rect.size.height + 28))
path.addLine(to: CGPoint(x: 70, y: rect.size.height + 28))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.path = path.cgPath
layer.addSublayer(shapeLayer)
}
func touchDown(button: ButtonContinue, event: UIEvent) {
if let touch = event.touches(for: button)?.first {
let location = touch.location(in: button)
if path.contains(location) == false {
button.cancelTracking(with: nil)
}
}
}
}
答
只要把你的项目的资产提供的图像。并将按钮图像设置为资产中的图像。
self.imageView.image = UIImage(named: "imageName")
如果你想改变,你可以设置图像的线条颜色的图像渲染alwaysTemplate
self.imageView?.image = UIImage(named: "imageName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
self.imageView?.tintColor = .red
你为什么需要这样说?使用图像不是更简单吗? –
你真的想/需要检查触摸位于箭头框内吗?我只是使用一个图像。 –