UIButton 系统样式选中状态,保留图片和背景
Posted
技术标签:
【中文标题】UIButton 系统样式选中状态,保留图片和背景【英文标题】:UIButton System style selected state, keep image and background 【发布时间】:2019-11-21 08:41:53 【问题描述】:使用 UIButton 的 System 样式时(不,我不想使用 Custom 样式,因为系统提供动画等...)
系统按钮的选中状态添加背景并移除图像
这是默认状态
我想实现这样的选定样式,其中选定时的外观与自定义按钮相同
【问题讨论】:
除了动画之外,自定义按钮还处理启用/选中状态下图像的不同颜色...更接近我的是系统处理 【参考方案1】:好的,终于把那个弄出来了,关键是不允许切换到选中状态
class ControlButton: UIButton
var sImage: UIImage?
var dImage: UIImage?
override func awakeFromNib()
super.awakeFromNib()
sImage = image(for: .selected)
dImage = image(for: .normal)
override open var isSelected: Bool
set
if newValue
setImage(sImage, for: .normal)
else
setImage(dImage, for: .normal)
get
return false
【讨论】:
【参考方案2】:添加此类并将其设置为您的按钮类
class KButton: UIButton
var view: UIButton!
@IBInspectable public var textPadding: CGFloat = 5.0
didSet
layoutSubviews()
@IBInspectable public var circleRadius: CGFloat = 10
didSet
layoutSubviews()
@IBInspectable public var circleWidth: CGFloat = 2.0
didSet
layoutSubviews()
@IBInspectable public var currentState: Bool = false
didSet
layoutSubviews()
override func layoutSubviews()
super.layoutSubviews()
if view != nil
view?.removeFromSuperview()
view = UIButton(frame: CGRect(x: -(self.frame.height) - textPadding, y: 0, width: self.frame.height, height: self.frame.height))
view.backgroundColor = UIColor.clear
let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.height/2, y: view.frame.height/2), radius: circleRadius, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = self.tintColor.cgColor
shapeLayer.lineWidth = circleWidth
view.layer.addSublayer(shapeLayer)
if currentState
let circlePath1 = UIBezierPath(arcCenter: CGPoint(x: view.frame.height/2, y: view.frame.height/2), radius: (circleRadius - (circleWidth * 2)), startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer1 = CAShapeLayer()
shapeLayer1.path = circlePath1.cgPath
shapeLayer1.fillColor = self.tintColor.cgColor
shapeLayer1.strokeColor = self.tintColor.cgColor
shapeLayer1.lineWidth = circleWidth
view.layer.addSublayer(shapeLayer1)
self.addSubview(view)
然后在你点击动作
@IBAction func buttonClicked(_ sender: KButton)
sender.currentState = !sender.currentState
确保选择类型为 KButton
【讨论】:
以上是关于UIButton 系统样式选中状态,保留图片和背景的主要内容,如果未能解决你的问题,请参考以下文章