在Swift中创建一个带有填充底部的按钮图像

时间:2017-05-18 15:21:06

标签: swift image button swift3 background

我正在创建一个过滤器系统。

我试图这样做:

enter image description here

目前我正在使用setBackgroundImage功能,而我在图片下面没有这个小矩形:

filterButton.setBackgroundImage(imageForButton, for: .normal)

我尝试过这样的功能:

filterButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)

但如果我保留setBackgroundImage func,它就无效了。

如果我使用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)

      }

1 个答案:

答案 0 :(得分:1)

看起来你正试图在一个UIButton中做所有事情。我建议创建一个自定义元素来处理这个问题。 您可以通过以下几种方法设置具有所需功能的自定义UI元素:

  1. 使用UILabel显示带有彩色背景的“A1”标签,并在单独的UIImageView中显示图像本身。这些可以用不可见的UIButton覆盖,以接收touchUpInside事件并传递给您的控制器。
  2. 或者,您可以创建自定义UIControl添加添加UILabel和UIImageView作为子视图。禁用子视图上的userInteraction应允许UIControl接收触摸事件。这可以包含在单个可重用的类中,就像它是一个UI元素一样。