Alex Alex - 17 days ago 5
iOS Question

Creating views using viewWithTag Swift Optionals issues

I'm using a GitHub project that recreates the "chips" component that exists in Android in a iOS project. I'm trying to write this Objective-C code in Swift:

NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"TokenView" owner:nil options:nil];
UIView *view = nibContents[0];
UILabel *label = (UILabel *)[view viewWithTag:2];
UIButton *button = (UIButton *)[view viewWithTag:3];

[button addTarget:self action:@selector(tokenDeleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

label.text = self.tokens[index];
CGSize size = [label sizeThatFits:CGSizeMake(1000, 40)];
view.frame = CGRectMake(0, 0, size.width + 97, 40);
return view;


This is what I have so far.

let view = Bundle.main.loadNibNamed("TokenView", owner: nil, options: nil)?[0] as? UIView

if let imageView = UIImageView().viewWithTag(1) as? UIImageView {
imageView.image = UIImage(named: "pic.png")
}

if let label = UILabel().viewWithTag(2) as? UILabel {
label.text = (tokens[Int(index)] as! NSString) as String
let size = (label.sizeThatFits(CGSize(width: 1000, height: 40)))
view?.frame = CGRect(x: 0, y: 0, width: size.width + 97, height: 40)
}

if let deleteButton = UIButton().viewWithTag(3) as? UIButton {
deleteButton.addTarget(self, action: #selector(tokenDeleteButtonPressed(tokenButton:)), for: .touchUpInside)
}

return view


The problem I'm having is that the UILabel, UIButton and UIImageView are all nil and I can't seem to figure out why.
When I try to debug it and print the description of each view all I get is UIImageView (out of scope)

I've been reading, watching videos on optionals, and I understand how to use it for simple cases, but this seems to be a little more complicated.

Answer

You are creating a label,Button and imageview . So your code should be like below . I am assuming that label,Button and imageview are sub-views of TokenView

 let view = Bundle.main.loadNibNamed("TokenView", owner: nil, options: nil)?[0] as? UIView

if let imageView = view?.viewWithTag(1) as? UIImageView {
        imageView.image = UIImage(named: "pic.png")
    }

    if let label =view?.viewWithTag(2) as? UILabel {
        label.text = (tokens[Int(index)] as! NSString) as String
        let size = (label.sizeThatFits(CGSize(width: 1000, height: 40)))
        view?.frame = CGRect(x: 0, y: 0, width: size.width + 97, height: 40)
    }

    if let deleteButton = view?.viewWithTag(3) as? UIButton {
        deleteButton.addTarget(self, action: #selector(tokenDeleteButtonPressed(tokenButton:)), for: .touchUpInside)
    }
Comments