Duy Khanh Nguyen
Duy Khanh Nguyen

Reputation: 55

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!

P/s: Problem solved with @Janmenjaya answer, here is my code, still have a little bit stuck with y position.

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

Upvotes: 2

Views: 80

Answers (1)

Janmenjaya
Janmenjaya

Reputation: 4163

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 ...

Upvotes: 1

Related Questions