【发布时间】:2019-08-27 04:01:00
【问题描述】:
我正在创建具有不同图像形状的按钮...一切正常,但如果创建了菱形形状,您可以单击按钮的透明部分。我设法设置阴影以尊重按钮的形状,使其看起来突出显示,但如何应用它以便在交互时忽略按钮的透明部分?
我找到了一些答案,但我不使用路径来创建 UIButton 形状,而是使用 UIButton 上的图像。
下面是如何创建我的一个按钮并设置发光
extension UIbutton {
func createSquareButton(buttonPositionX: CGFloat, buttonPositionY: CGFloat, buttonWidth: CGFloat, buttonHeight: CGFloat, buttonTitle: String) {
let button = self
button.isUserInteractionEnabled = true
button.frame = CGRect(x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight)
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.setTitleColor(UIColor.black, for: .highlighted)
button.alpha = 1.0
button.titleLabel?.font = .systemFont(ofSize: 20)
button.backgroundColor = nil
button.tintColor = Style.PurpleColor
let image = UIImage(named: "Plain Square")
let imageView = UIImageView(image: image)
imageView.setImageColor(color: Style.PurpleColor)
button.setBackgroundImage(imageView.image, for: .normal)
button.setBackgroundImage(imageView.image, for: .selected)
button.setBackgroundImage(imageView.image, for: .highlighted)
}
}
func buttonGlow(sender: CustomBtn){
for button in buttonArray {
if button.UUIDtag == currentSelectedMarkerUUID {
sender.layer.shadowColor = button.tintColor.cgColor
sender.layer.shadowRadius = 15
sender.layer.shadowOpacity = 1.0
sender.layer.masksToBounds = false
} else {
let otherBtn = tmpButtonPicked(uuid: button.UUIDtag!)
otherBtn.layer.shadowColor = UIColor.clear.cgColor
otherBtn.layer.shadowRadius = 0
}
}
}
extension UIImageView {
func setImageColor(color: UIColor) {
let templateImage = self.image?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
}
【问题讨论】:
-
使用图像没有简单的方法。你最好使用路径。如果您一心想这样做,那么我建议您手动查找按钮内的接触点 (stackoverflow.com/a/43042911/7842542),然后决定是否采取行动
标签: ios swift uibutton user-interaction