ios - 更改 UIButton 矩形而不使用drawRect

标签 ios swift uibutton uibezierpath drawrect

我在 xib 上有一个 UIButton,它是一个矩形,我想更改它的框架以具有像箭头一样的角,但将其保留在 xib 上(来自界面生成器),我该怎么做?

我知道我可以使用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)
            }
        }
    }
}

最佳答案

只需将您提供的图像放入项目的 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/

相关文章:

ios - 从 Storyboard 中撤消堆栈 View

ios - 从选项卡栏弹出(如 Yelp 应用程序)

swift - Rxswift + Moya + Moya-ObjectMapper fatal error

ios - 使用参数初始化 UIButton

ios - 在 UITableViewHeaderFooterView 中有一个按钮

ios - loading... iPad 上的应用程序安装卡住了

ios - 如何在 AFNetworking 的帮助下发出 Twilio api Post 请求?

swift - 如何修复 swift 3 嵌套的一般错误

Swift NSURLSession HTTPS 自签名 - 请求永远不会到达服务器

ios - swift 4 : UIButton not working