为多个数据创建和自定义一个 UIButton

Create and custom one UIButton for multiple data

我有一组内容如下:

数组 = [姓名 1、姓名 2、姓名 3...]

并且我想在按钮的标签上显示这些内容。问题是如果我的数组有很多项目并且我不想创建那么多按钮,那将是硬核。所以请任何人都可以帮助我找到为这些数据生成一个通用按钮实例的方法。就像如果我的数组有 2 个项目,视图将显示 2 个按钮等等...非常感谢!

P/s:@Janmenjaya 回答解决了问题,这是我的代码,y 位置仍然有点卡住。

func displayFileList() {
    for i in 0..<fileIdList.count {
        let yRef : CGFloat = 35
        let title = String(fileIdList.indexOf(i))
        let button = UIButton(frame: CGRect(x: 0, y: yRef * CGFloat(i), width: 919, height: 30))
        button.setTitle(title, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.backgroundColor = UIColor.yellowColor()
        button.layer.borderWidth = 1;
        button.layer.borderColor = UIColor.blackColor().CGColor
        self.fileButtonContainView.addSubview(button)
    }
}

您可以遍历数组并根据数组内容以编程方式创建带有动态标题的按钮。

遵循示例代码

示例代码片段:

    arrData = NSMutableArray();

    arrData.addObject("Test0");
    arrData.addObject("Test1");
    arrData.addObject("Test2");
    arrData.addObject("Test3");
    arrData.addObject("Test4");

    var yRef : CGFloat = 100

    for i in 0..<arrData.count{

        let title = arrData.objectAtIndex(i);

        let btn = UIButton(type: .Custom);
        btn.frame = CGRectMake(100, yRef, 100, 40);
        btn.setTitle(title as? String, forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.grayColor();
        self.view.addSubview(btn);

        yRef += CGRectGetHeight(btn.frame) + 10;
    }

输出:

希望对您有所帮助

编码愉快...