Duy Khanh Nguyen Duy Khanh Nguyen - 1 year ago 124
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 Source

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();


    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();

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

Output : enter image description here

Hope it helps

Happy coding ...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download