在Swift中创建底部填充的按钮图像
我正在创建一个过滤器系统 我正试图做到这一点: 目前我正在使用setBackgroundImage func,图片下方没有这个小矩形:在Swift中创建底部填充的按钮图像,swift,image,button,swift3,background,Swift,Image,Button,Swift3,Background,我正在创建一个过滤器系统 我正试图做到这一点: 目前我正在使用setBackgroundImage func,图片下方没有这个小矩形: filterButton.setBackgroundImage(imageForButton, for: .normal) 我尝试过这样的函数: filterButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0) 但是如果我保持挫折的形象是无效的 如果我使用
filterButton.setBackgroundImage(imageForButton, for: .normal)
我尝试过这样的函数:
filterButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
但是如果我保持挫折的形象是无效的
如果我使用setImage,结果很好,但是单击不再有效
filterButton.setImage(imageForButton, for: UIControlState.normal)
你有办法做我想做的事吗
完整片段:
for i in 0 ..< CIFilterNames.count {
itemCount = i
// Button properties
let filterButton = UIButton(type: .custom)
// filterButton.frame = CGRectMake(xCoord, yCoord, buttonWidth, buttonHeight)
filterButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
filterButton.tag = itemCount
filterButton.addTarget(self, action: #selector(self.filterButtonTapped(_:)), for: .touchUpInside)
// filterButton.layer.cornerRadius = 6
// filterButton.clipsToBounds = true
let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: originalImage.image!)
let filter = CIFilter(name: "\(CIFilterNames[i])" )
filter!.setDefaults()
filter!.setValue(coreImage, forKey: kCIInputImageKey)
let filteredImageData = filter!.value(forKey: kCIOutputImageKey) as! CIImage
let filteredImageRef = ciContext.createCGImage(filteredImageData, from: filteredImageData.extent)
let imageForButton = UIImage(cgImage: filteredImageRef!)
filterButton.backgroundColor = UIColor.red
filterButton.setImage(imageForButton, for: UIControlState.normal)
//filterButton.imageEdgeInsets = UIEdgeInsets(top: 0,left: 0,bottom: 15,right: 0)
//filterButton.setBackgroundImage(imageForButton, for: .normal)
filterButton.setTitle("A\(i)", for: .normal)
// filterButton.backgroundImage.contentMode = .scaleAspectFill
filterButton.setTitleColor(UIColor(red: 22 / 255, green: 21 / 255, blue: 22 / 255, alpha: 1), for: .normal)
filterButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
filterButton.titleEdgeInsets.top = 140
// Add Buttons in the Scroll View
xCoord += buttonWidth + gapBetweenButtons
filtersScrollView.addSubview(filterButton)
}
看起来您正试图在一个按钮中完成所有操作。我建议创建一个自定义元素来处理这个问题。 有几种方法可以设置具有所需功能的自定义UI元素: 使用UILabel以彩色背景显示A1标签,并在单独的UIImageView中显示图像本身。这些可以覆盖一个不可见的UIButton来接收touchUpInside事件并传递给控制器。 或者,您可以创建自定义UIControl添加添加UILabel和UIImageView作为子视图。禁用子视图上的用户交互应允许UIControl接收触摸事件。这可以包含在单个可重用类中,就像它是一个UI元素一样。
图像和过滤器按钮是两个独立的元素吗?你能分享一段更大的代码吗?谢谢你的回答,是的,这是两个不同的元素。我用更多的代码编辑了我的问题,这是一个显示多个按钮的函数,它非常简单。。。我觉得自己很愚蠢。。。我刚刚用相同的目标创建了第二个按钮。。。非常感谢你!令人惊叹的这比我的建议还要简单。有时候简单是最好的。