工作中我们常常碰到这样的点击按钮,实现方法有很多种,今天给大家介绍下我这边使用UIButton titleEdgeInsets和imageEdgeInsets的实现方案。
直接上代码,方法调用前先设置图片和文字
@objcfuncchangeImageTitleLocation(type: ChangeButtonImageLocationType,distance: CGFloat) {
layoutIfNeeded()
letbtnWidth =frame.width
letbtnHeight =frame.height
letimageFrame =imageRect(forContentRect:CGRect(x:0,y:0,width: btnWidth,height: btnHeight))
lettitleFrame =titleRect(forContentRect:CGRect(x:0,y:0,width: btnWidth,height: btnHeight))
iftype == .top|| type == .bottom{
lettitleDistance = (btnWidth-titleFrame.width)/2- titleFrame.origin.x
letimageDistance = (btnWidth-imageFrame.width)/2- imageFrame.origin.x
iftype == .top{
lettitleHDistance = (btnHeight + imageFrame.size.height- titleFrame.size.height+ distance)/2- titleFrame.origin.y
letimageHDistance = (btnHeight - imageFrame.size.height- titleFrame.size.height- distance)/2- imageFrame.origin.y
titleEdgeInsets=UIEdgeInsets(top: titleHDistance,left: titleDistance,bottom: -titleHDistance,right: -titleDistance)
imageEdgeInsets=UIEdgeInsets(top: imageHDistance,left: imageDistance,bottom: -imageHDistance,right: -imageDistance)
}else{
lettitleHDistance = (btnHeight - imageFrame.size.height- titleFrame.size.height- distance)/2- titleFrame.origin.y
letimageHDistance = (btnHeight - imageFrame.size.height+ titleFrame.size.height+ distance)/2- imageFrame.origin.y
titleEdgeInsets=UIEdgeInsets(top: titleHDistance,left: titleDistance,bottom: -titleHDistance,right: -titleDistance)
imageEdgeInsets=UIEdgeInsets(top: imageHDistance,left: imageDistance,bottom: -imageHDistance,right: -imageDistance)
}
}elseiftype == .right{
lettitleDistance = (btnWidth-titleFrame.width-imageFrame.width-distance)/2- titleFrame.origin.x
letimageDistance = (btnWidth+titleFrame.width-imageFrame.width+distance)/2- imageFrame.origin.x
titleEdgeInsets=UIEdgeInsets(top:0,left: titleDistance,bottom:0,right: -titleDistance)
imageEdgeInsets=UIEdgeInsets(top:0,left: imageDistance,bottom:0,right: -imageDistance)
}else{
lettitleDistance = (btnWidth-titleFrame.width+imageFrame.width+distance)/2- titleFrame.origin.x
letimageDistance = (btnWidth-titleFrame.width-imageFrame.width-distance)/2- imageFrame.origin.x
titleEdgeInsets=UIEdgeInsets(top:0,left: titleDistance,bottom:0,right: -titleDistance)
imageEdgeInsets=UIEdgeInsets(top:0,left: imageDistance,bottom:0,right: -imageDistance)
}
}