我在 xib 上有一个 UIButton,它是一个矩形,我想更改它的框架以具有像箭头一样的角,但将其保留在 xib 上(来自界面生成器),我该怎么做?
我知道我可以使用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)
}
}
}
}
最佳答案
只需将您提供的图像放入项目的 Assets 中即可。并将按钮图像设置为资源中的图像。
self.imageView.image = UIImage(named: "imageName")
如果您想更改图像线条的颜色,可以将图像渲染设置为alwaysTemplate
self.imageView?.image = UIImage(named: "imageName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
self.imageView?.tintColor = .red
关于ios - 更改 UIButton 矩形而不使用drawRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46990273/