我正在创建一个过滤器系统。
我正在尝试这样做:
目前我正在使用 setBackgroundImage 函数,但图片下方没有这个小矩形:
filterButton.setBackgroundImage(imageForButton, for: .normal)
我试过这样的函数:
filterButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
但如果我保留 setBackgroundImage 函数,则无效。
如果我使用 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)
}
最佳答案
看起来您正在尝试在单个 UIButton 中完成所有操作。我建议创建一个自定义元素来处理这个问题。 有几种方法可以设置具有所需功能的自定义 UI 元素:
- 使用 UILabel 显示带有彩色背景的“A1”标签,并在单独的 UIImageView 中显示图像本身。这些可以用不可见的 UIButton 覆盖以接收 touchUpInside 事件并传递给您的 Controller 。
- 或者,您可以创建自定义 UIControl 添加 UILabel 和 UIImageView 作为 subview 。在 subview 上禁用 userInteraction 应该允许 UIControl 接收触摸事件。这可以包含在单个可重用类中,就好像它是一个 UI 元素一样。
关于swift - 在 Swift 中创建带有填充底部的按钮图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44051808/