Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 为按钮指定一个字符串。敏捷的_Ios_Swift - Fatal编程技术网

Ios 为按钮指定一个字符串。敏捷的

Ios 为按钮指定一个字符串。敏捷的,ios,swift,Ios,Swift,我有四个按钮,它们在for循环中以相同的编程方式创建: let moreButton = UIButton(type: .system) moreButton.frame = CGRect(x: 0, y: 0, width: 80, height: 25) moreButton.center.x = self.view.center.x + 115 moreButton.center.y = OficerAgendas.center.y + CGFloat(yOffset +

我有四个按钮,它们在for循环中以相同的编程方式创建:

  let moreButton = UIButton(type: .system)
  moreButton.frame = CGRect(x: 0, y: 0, width: 80, height: 25)
  moreButton.center.x = self.view.center.x + 115
  moreButton.center.y = OficerAgendas.center.y + CGFloat(yOffset + 30)
  moreButton.contentMode = .scaleAspectFit
  moreButton.layer.cornerRadius = 5
  moreButton.tintColor = UIColor.white
  moreButton.backgroundColor = UIColor(red:0.76, green:0.49, blue:0.49, alpha:1.0)
  moreButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
  moreButton.setTitle("My Opinion", for: UIControl.State.normal)
  moreButton.addTarget(self, action: #selector(mainPage.buttonAction(_:)), for: .touchUpInside)
  self.view.addSubview(moreButton)
我有一个内部点击润色的基本代码

@objc func buttonAction(_ sender:UIButton!)
{
    print("Button tapped")
}

我希望代码能够区分按下的按钮(因为它们都是“moreButton”,所以我不能创建单独的按钮操作代码)。理想情况下,我可以指定创建按钮的for循环的迭代(它是1…items类型循环中的for项)。有什么方法可以做到这一点吗?

您可以为按钮设置标签:

moreButton.tag = 1 
(如果使用迭代,则为变量)

然后在这个方法中,你可以用

switch sender.tag
{
    case 1: print("1")     // button 1 clicked
        break
    case 2: print("2")     // button 2 clicked
        break
    default: print("...")
}

谢谢,我刚刚发现了.tag属性,它工作得非常好!