在没有drawRect的情况下更改UIButton rect

时间:2017-10-28 13:30:47

标签: ios swift uibutton uibezierpath drawrect

我在xib上有一个UIButton是一个矩形,我想改变它的框架有一个像角一样的箭头,但是把它保留在xib上(来自界面构建器),我该怎么做? / p>

我知道我可以在drawRect中使用UIBezierPath做到这一点,但这只是创建一个自定义形状并从代码中添加它。

还有其他办法吗?

enter image description here 这是我的自定义按钮类代码:

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)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

只需将您提供的图像放在项目的资产中即可。并将按钮图像设置为资源中的图像。

self.imageView.image = UIImage(named: "imageName")

如果您想更改图像线条的颜色,可以将图像渲染设置为alwaysTemplate

self.imageView?.image = UIImage(named: "imageName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
self.imageView?.tintColor = .red