Search code examples
dynamicswift3uitextview

swift 3 How to add UITextView programmatically then remove it when click the button?


I am newbie on swift 3. I have this situation: I need to create textview dynamically also the remove button below it...so there is button to add field (textview) dynamically then there's button below it to remove it..and I put those on view.. Let say "placeholderCD"

enter image description here

But the problem is..how or what action i need to put when the remove button click? because we can not assigned the id of dynamically button right? so my code like below :

func AddCommentItem(sender:UIButton){
    /** CREATE TEXT VIEW **/
    let textView: UITextView = UITextView(frame: CGRect(x: 0, y: (newX + 20), width: 311.00, height: 50.00));
    textView.textAlignment = NSTextAlignment.justified
    //textView.backgroundColor = UIColor.lightGray
    let borderColor = UIColor.lightGray
    textView.layer.borderColor = borderColor.cgColor
    textView.layer.borderWidth = 1.0
    textView.tag = tagname
    /** CREATE TEXT VIEW **/

    /** CREATE REMOVE TEXT VIEW **/
    let btnRemove: UIButton = UIButton(frame: CGRect(x: 240, y: (newX + 52), width: 100, height: 50))
    //btnRemove.backgroundColor = UIColor.green
    btnRemove.setTitle("Remove", for: .normal)
    btnRemove.titleLabel?.font = btnRemove.titleLabel?.font.withSize(10)
    btnRemove.tag = tagname

    btnRemove.setTitleColor(UIColor.gray, for: .normal)
    btnRemove.addTarget(self, action: #selector(btnRemoveComment), for: .touchUpInside)
    //btnRemove.tag = 1

    /** CREATE REMOVE TEXT VIEW **/

    cell.placeholderCD.addSubview(textView)
    cell.placeholderCD.addSubview(btnRemove)
}

func btnRemoveComment(Sender:UIButton) {
   /** HOW I REMOVE THE Related text view object with this action **/
}

Solution

  • you can remove the textview by tag

    cell.placeholderCD.viewWithTag(yourTag)?.removeFromSuperview()