Duy Khanh Nguyen Duy Khanh Nguyen - 27 days ago 15
iOS Question

Create and custom one UIButton for multiple data

I have an array of content as follow:

array = [Name1,Name2,Name3...]

and I want to display these content on the label of the button. The problem is it will be hardcore if my array have many item and I dont want to create so many button like that. So please anyone can help me to findout the way to generate one common button instance for these data. Like if my array have 2 item, the view will display 2 buttons and so on... THank you very much!

Answer

You can loop through the array and create the button programmatically with dynamic title based on the array contents.

Follow the sample code

Sample code snippet :

    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;
    }

Output : enter image description here

Hope it helps

Happy coding ...

Comments