在运行时添加UI元素的问题

时间:2016-10-19 06:27:41

标签: ios swift autolayout storyboard

我遇到这种情况:

enter image description here

滚动视图中的粉红色视图我想要的是:

当我点击“添加”按钮时,我希望创建另一个粉红色视图对象(这没有问题)并将其设置在第一个粉红色视图对象设置自动布局下方(它与之前的粉红色视图之间的垂直空间)对象,尾随空间.....)但我无法做到这一点。

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我不确定在向scrollview添加视图时遇到问题。以下是在运行时将按钮添加到scrollview的示例。您可以使用相同的代码添加粉红色视图。

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
{

    var pickerviewObj : UIPickerView!=UIPickerView()
    var scrlview: UIScrollView = UIScrollView();
    var cotentView : UIView = UIView();
    var arrdata :NSMutableArray=["1","2","3","4","5","6","7","8","9","10"]
    var dctButtons : NSMutableDictionary!=NSMutableDictionary()
    var    ContentViewconstraintheight : NSLayoutConstraint = NSLayoutConstraint()
    var xPos,ypos: NSInteger!
    var SelctedTag : NSInteger!

    var width: Double!

    // var colors = ["Red","Yellow","Green","Blue"]

    func getCalculatedHeightForScren(height : CGFloat) -> CGFloat {

        return (height *  self.view.frame.size.height/568  );

    }
    func disableAutoResizingMasks() {
        self.pickerviewObj.translatesAutoresizingMaskIntoConstraints = false
        self.scrlview.translatesAutoresizingMaskIntoConstraints = false
        self.cotentView.translatesAutoresizingMaskIntoConstraints = false;
    }
    override func viewDidLoad()
    {
        super.viewDidLoad()
        let  pickerHeight  = getCalculatedHeightForScren(height: 50)
        self.pickerviewObj = UIPickerView(frame: CGRect(x: 0, y: self.view.frame.size.height-pickerHeight, width: self.view.frame.size.width, height: pickerHeight) )
        self.view.addSubview(self.pickerviewObj);
        pickerviewObj.backgroundColor = UIColor.white;
        pickerviewObj.showsSelectionIndicator = true;
        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.default;

        toolBar.isTranslucent = true
        toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
        toolBar.sizeToFit()

        self.view.addSubview(self.scrlview)
        self.scrlview.addSubview(self.cotentView);
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.DonePicker))

        toolBar.setItems([  spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        toolBar.frame = CGRect(x: 0, y: self.view.frame.size.height-pickerHeight-44, width: self.view.frame.size.width, height: 44);
        self.view.addSubview(toolBar);
        pickerviewObj.dataSource = self;
        pickerviewObj.delegate = self;


        //add constraints to PickerView

        let constraintCenterX =    NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);
        let constraintBottom =    NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.bottom, multiplier: 1, constant:0);

        let constraintWidth =    NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);

        let constraintHeight =    NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.height , relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.height, multiplier: (200/568), constant:0);




        //add constraints to ScrollView


        let scrollconstraintCenterX =    NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);
        let scrollconstraintBottom =    NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: toolBar     , attribute: NSLayoutAttribute.top, multiplier: 1, constant:0);

        let scrollconstraintWidth =    NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);

        let scrollconstraintTop =    NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.top , relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.top, multiplier:1, constant:0);

        //add constraints to ScrollView's contentView

        let ContentViewconstrainttop =    NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview     , attribute: NSLayoutAttribute.topMargin, multiplier: 1, constant:0);
        let ContentViewconstraintBottom =    NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview     , attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, constant:0);

        let ContentViewconstraintleft =    NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.trailing , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview     , attribute: NSLayoutAttribute.trailing, multiplier: 1, constant:0);

        let ContentViewconstraintright =    NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.leading , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview     , attribute: NSLayoutAttribute.leading, multiplier: (200/568), constant:0);


        let ContentViewconstraintWidth =    NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview     , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);
        self.ContentViewconstraintheight =    NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil     , attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant:100);



        //add constraints to toolBar

        let toolconstraintCenterX =    NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);

        let toolconstraintBottom =    NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.pickerviewObj     , attribute: NSLayoutAttribute.top, multiplier: 1, constant:0);

        let toolconstraintWidth =    NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view     , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);

        //activare all constraints


        NSLayoutConstraint.activate([constraintWidth,constraintHeight,constraintCenterX,constraintBottom,toolconstraintWidth,toolconstraintBottom,toolconstraintCenterX,scrollconstraintTop,scrollconstraintWidth,scrollconstraintCenterX,scrollconstraintBottom,ContentViewconstrainttop,ContentViewconstraintBottom,ContentViewconstraintleft,ContentViewconstraintright,ContentViewconstraintWidth,self.ContentViewconstraintheight]);
        self.view.layoutSubviews()
        self.disableAutoResizingMasks();
        toolBar.translatesAutoresizingMaskIntoConstraints = false

    }


    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }


    func getSorted(s1 : Any , s2 : Any) -> Bool{
        let str1 : String = s1 as! String
        let str2 : String = s2 as! String
        return Int(str1)! <  Int(str2)!;

    }
    //custom Logics to Update UI
    func addConstarintsToButton(btn : UIButton , yPos : CGFloat)
    {
        NSLayoutConstraint.deactivate(btn.constraints);
        btn.removeConstraints(btn.constraints);

        let width = ((self.view.frame.size.width-20)/2) - 30;
        let height = self.getCalculatedHeightForScren(height: 40);

        let constraintCenterX =    NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview     , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);

        let constrainttop =    NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.top , relatedBy: NSLayoutRelation.equal, toItem: self.cotentView     , attribute: NSLayoutAttribute.top, multiplier: 1, constant:yPos);

        let constraintWidth =    NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: nil     , attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: width);

        let constraintHeight =    NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.height , relatedBy: NSLayoutRelation.equal, toItem: nil     , attribute: NSLayoutAttribute.notAnAttribute, multiplier: height, constant:height);

        NSLayoutConstraint.activate([constraintCenterX, constrainttop,constraintWidth,constraintHeight])


        btn.translatesAutoresizingMaskIntoConstraints = false
    }
    func updateUIElements(tag : Int)
    {

        let arrKeys : NSMutableArray = NSMutableArray(array: dctButtons.allKeys, copyItems: true)
        let SortedKeys =     arrKeys.sorted(by: getSorted)

        var xPos :CGFloat = 10.0;
        var yPos :CGFloat = 50.0;
        let width = ((self.view.frame.size.width-20)/2) - 30;
        let height = self.getCalculatedHeightForScren(height: 40);

        xPos = (self.view.frame.size.width - width)/2;

        UIView.animate(withDuration: 0.5, animations:  {

            if(tag > 0)
            {
                let vw = self.cotentView.viewWithTag(tag)
                vw?.removeFromSuperview()

                let vw1 = self.cotentView.viewWithTag(tag + 100)
                vw1?.removeFromSuperview()
            }

            for key in SortedKeys {

                let  btn1 = self.dctButtons.object(forKey: key) as! UIButton
                btn1.frame = CGRect( x:xPos, y:yPos,width:width,height:height);
                if let testBtn = self.cotentView.viewWithTag(btn1.tag+100) as? UIButton
                {

                    let btnCross =  testBtn  ;
                    btnCross.frame = CGRect(x: xPos + btn1.frame.size.width + 5, y: yPos, width: 20, height: height);
                }


                self.ContentViewconstraintheight.constant = btn1.frame.size.height + 100;
                if let vw = self.cotentView.viewWithTag(btn1.tag) as? UIButton
                {
                    vw.removeFromSuperview();
                    self.cotentView.addSubview(btn1);
                    self.addConstarintsToButton(btn: btn1, yPos: yPos);

                }
                else{
                    self.cotentView.addSubview(btn1);
                    self.addConstarintsToButton(btn: btn1, yPos: yPos);

                }
                yPos  += height + 10

            }
            self.view.layoutSubviews()
            self.ContentViewconstraintheight.constant = yPos ;

        })


    }


    // Control event Methods....


    func btnClick(sender: UIButton!)
    {
        SelctedTag=sender.tag;
        print(SelctedTag)
        if sender.isSelected
        {
            return;
        }
        sender.isSelected = true;

        let ButtonClose = UIButton(frame: CGRect(x: sender.frame.origin.x + sender.frame.size.width + 5, y: sender.frame.origin.y, width: 20, height: sender.frame.size.height) )
        ButtonClose.tag = sender.tag + 100;
        ButtonClose.setTitle("X", for: UIControlState.normal)
        ButtonClose.backgroundColor = UIColor.gray
        ButtonClose.setTitleColor(UIColor.red, for: UIControlState.normal);
        ButtonClose.isUserInteractionEnabled = true;
        ButtonClose.addTarget(self, action: #selector(ViewController.btnClose(sender:)), for: UIControlEvents.touchUpInside);
        self.cotentView.addSubview(ButtonClose);

        let strVal = String(sender.tag)

        self.arrdata.remove(strVal)
        self.pickerviewObj.reloadComponent(0);

    }
    func DonePicker()
    {
        let selectedIndex = self.pickerviewObj.selectedRow(inComponent: 0);
        if (arrdata.count == 0 ||  selectedIndex < 0  || selectedIndex > arrdata.count )
        {
            return;
        }
        let x : String = arrdata[selectedIndex] as! String
        let tag = Int(x)!
        if let vw = self.cotentView.viewWithTag(tag) as? UIButton
        {
            return;
        }

        let btn = UIButton(type: UIButtonType.system);
        btn.isSelected = false;
        btn.tag =  tag
        btn.backgroundColor = UIColor.black;
        btn.setTitleColor(UIColor.white, for: UIControlState.normal)
        btn.addTarget(self, action:#selector(ViewController.btnClick(sender:)), for: UIControlEvents.touchUpInside)
        btn.setTitle("Field " + String(x), for: UIControlState.normal)
        btn.setTitleColor(UIColor.white, for: UIControlState.normal)
        btn.isUserInteractionEnabled = true;
        btn.center = self.pickerviewObj.center;
        dctButtons.setObject(btn, forKey: String(x) as NSCopying)
        self.pickerviewObj.reloadComponent(0);
        self.updateUIElements(tag: 0);
    }

    func btnClose(sender: UIButton!)
    {
        print((SelctedTag))
        let key = String(sender.tag - 100);
        dctButtons.removeObject(forKey: key);
        arrdata.add( key)
        let tmpArray = arrdata.sorted(by: getSorted)
        arrdata.removeAllObjects();
        arrdata.addObjects(from: tmpArray)
        self.pickerviewObj.reloadComponent(0);
        self.updateUIElements(tag: sender.tag - 100);

    }

    // Picker view Methods....

    func numberOfComponents(in pickerView: UIPickerView) -> Int
    {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return arrdata.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    {
        let x : String = arrdata[row] as! String
        return  "Field " + x
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        //        let x : Int = arrdata[row] as! Int
        //        arrButton.add(x)
        //        print(arrButton)

        //       self .numberOfButton(number: arrdata[row] as! Int)
        //       arrdata.removeObject(at: row)
        //       pickerView.reloadAllComponents()
    }

}

相关问题