【问题标题】:create a all but one item loop to apply effects创建一个除一项之外的所有项目循环以应用效果
【发布时间】:2019-12-23 02:17:19
【问题描述】:

我希望我的 swift 代码创建一种循环,除了用户声明的之外,所有项目都遵循该循环。因此,例如下面,我列出了 4 个按钮和 1 个与按钮链接的 objc 函数。在 b1 hit 我知道我可以写

b1.backgroundcolor = blue and b2.backgroundcolor = green, b3.backgroundcolor = green。 Butt 我想看看我是否可以做类似[b1!,b2,b3].forEach{$0.backgroundcolor = .green.}

import UIKit

class ViewController: UIViewController {

var b1 = UIButton()
var b2 = UIButton()
var b3 = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    [b1,b3,b2].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.backgroundColor = .blue
    }


    b1.addTarget(self, action: #selector(b1Hit), for: .touchUpInside)

}

@objc func b1Hit(){

    change all buttons background color to green except b1

}

}

【问题讨论】:

  • 根据 b1b2b3 在功能上的相似程度,您可以使用 sender 参数 (buttonHit(sender: UIButton)) 创建一个通用函数,并使用sender 参数以了解 3 个按钮中的哪一个被按下。从那里,您可以进行循环,同时知道要跳过哪个按钮。

标签: arrays swift loops foreach except


【解决方案1】:

选项 1:使用 for inwhere 子句

使用带有where 子句的for in 循环来排除您要排除的那个:

// change all buttons background color to green except b1
for button in [b1, b2, b3] where button != b1 {
    button.backgroundColor = .green
}

选项 2:使用 Setsubtracting

Set([b1, b2, b3]).subtracting([b1]).forEach {
    $0.backgroundColor = .green
}

for button in Set([b1, b2, b3]).subtracting([b1]) {
    button.backgroundColor = .green
}

【讨论】:

  • 这正是我想要的。
【解决方案2】:

您可以做的是标记按钮并使用条件语句来确定在循环时更改颜色的按钮:

例如,如果您的 buttonArray 是 [b1,b2,b3]

var buttonArray : [UIButton]!

b1.tag = 1
b2.tag = 2
b3.tag = 3

func b1Hit(sender: UIButton) {

   buttonArray.forEach {

     if $0.tag != sender.tag {

       //change color

     }

   }    

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2020-06-19
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多