jeudi 4 février 2016

Swift: How do I arrange programatically added checkboxes?

I'm creating an iOS app using Swift, one with checkboxes. Currently, I've placed them inside a view (constrained and all), in the hopes that they would stay there and not mess up the rest of my app. Here's my code so far:

// UI
let lCheckboxHeight: CGFloat = 44.0;
let lCheckboxWidth: CGFloat = 180.0;

let waterSampleTreatmentTitles = ["i - Untreated", "ii - Acidified", "iii - Airfree", "iv - Filtered, Untreated","v - Filtered, Acidified","Stable Isotopes","Others"];

let lNumberOfCheckboxes = waterSampleTreatmentTitles.count

var lFrame = CGRectMake(0, 0, self.view.frame.size.width, lCheckboxHeight);

for (var counter = 0; counter < lNumberOfCheckboxes; counter++) {
    let lCheckbox = Checkbox(frame: lFrame, title: waterSampleTreatmentTitles[counter], selected: false);
    lCheckbox.mDelegate = self;
    lCheckbox.tag = counter;
    if (waterSampleTreatmentTitles[counter] == "i - Untreated" && self.flagUntreated == true){
        lCheckbox.selected = true
    }
    else if (waterSampleTreatmentTitles[counter] == "ii - Acidified" && self.flagAcidified == true){
        lCheckbox.selected = true
    }
    else if (waterSampleTreatmentTitles[counter] == "iii - Airfree" && self.flagAirfree == true){
        lCheckbox.selected = true
    }
    else if (waterSampleTreatmentTitles[counter] == "iv - Filtered, Untreated" && self.flagFilterUntreat == true){
        lCheckbox.selected = true
    }
    else if (waterSampleTreatmentTitles[counter] == "v - Filtered, Acidified" && self.flagFilterAcid == true){
        lCheckbox.selected = true
    }
    else if (waterSampleTreatmentTitles[counter] == "Stable Isotopes" && self.flagStabIso == true){
        lCheckbox.selected = true
    }
    else if (waterSampleTreatmentTitles[counter] == "Others" && self.flagOthers == true){
        lCheckbox.selected = true
    }
    self.chemistryProductionWell.viewSampTreat.addSubview(lCheckbox);
    lFrame.origin.y += lFrame.size.height;
}

Currently, this creates a list of checkboxes, which spills past the view I made, and just generally makes a mess of the app. The view is long enough for maybe two checkboxes vertically, but not eight.

enter image description here

How do I make it such that the checkboxes are arranged horizontally? I've tried replacing the following code:

lFrame.origin.y += lFrame.size.height;

With this:

lFrame.origin.x += lCheckboxWidth

But that doesn't take into account that the text for the checkboxes aren't the same length, and of course ignores the width restriction as well.

enter image description here

How do I make it such that if the checkbox length exceeds the view, it would drop down to the next line?

Thanks.




Aucun commentaire:

Enregistrer un commentaire