如何禁用ScrollView项目上的多个按钮颜色选择?

时间:2018-07-27 18:12:49

标签: ios swift xcode button uiscrollview

我正在开发一个照片编辑器移动应用程序,让用户单击滚动视图内的项目以在其上方显示较大的图像。

问题是当我点击多个项目时,它会一直显示相同的蓝色。

我要执行的操作是禁用多个选择,以便在滚动视图中的每个项目上一次只显示一种颜色。

这是我一直在使用的功能:

func ScrollFunctions() {


    var xCoord: CGFloat = 13
    let yCoord: CGFloat = 7
    let buttonWidth:CGFloat = 60
    let buttonHeight: CGFloat = 60
    let gapBetweenButtons: CGFloat = 5


    var itemCount = 0

    for i in 0..<CIFilterNames.count {
        itemCount = i

        // Button properties

        let filterButton = UIButton(type: .custom)
        filterButton.frame = CGRect(xCoord, yCoord, buttonWidth, buttonHeight)
        filterButton.tag = itemCount
        filterButton.addTarget(self, action: #selector(LooksViewController.filterButtonTapped(sender:)), for: .touchUpInside)
        filterButton.layer.cornerRadius = 0
        filterButton.clipsToBounds = true

        // Create filters for each button

        currentFilter = CIFilter(name: "\(CIFilterNames[i])" )
        let ciContext = CIContext(options: nil)
        let coreImage = CIImage(image: imagePassed)
        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!);
        // Assign filtered image to the button
        filterButton.setBackgroundImage(imageForButton, for: .normal)


        // Add Buttons in the Scroll View
        xCoord +=  buttonWidth + gapBetweenButtons
        filtersScrollView.addSubview(filterButton)
    }

    // Resize Scroll View
    filtersScrollView.contentSize = CGSize(buttonWidth * CGFloat(itemCount+2), yCoord)

}

这是您点击滚动视图项目时的功能。在这里,我一直在尝试'if else'语句,例如,如果按钮处于选中状态,则显示边框的宽度和颜色,否则返回false,但这没有用。有什么想法吗?

@objc func filterButtonTapped(sender: UIButton) {
    let button = sender as UIButton
    button.layer.borderWidth = 2
    button.layer.borderColor = #colorLiteral(red: 0.1882352941, green: 0.6392156863, blue: 0.6705882353, alpha: 1)
    imgView.image = imagePassed
    toolBar.isHidden = true
    yesAndNoToolBar.isHidden = false
    imgView.image = button.backgroundImage(for: UIControlState.normal)

}

1 个答案:

答案 0 :(得分:-1)

好的,您可以像下面那样接受一个成员变量。

var lastSelectedButton: UIButton?

现在在filterButtonTapped(sender: UIButton)函数中,检查lastSelectedButton

let button = sender as UIButton
if let button1 = lastSelectedButton {
// Deselect or reset this button1 color.
} 
lastSelectedButton = button
// Do your stuff here what you are doing now.

如有任何疑问,请发表评论。