我正在使用GitHub项目重新创建"芯片" iOS项目中Android中存在的组件。我试图在Swift中编写这个Objective-C代码:
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;
这是我到目前为止所拥有的。
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
我遇到的问题是UILabel,UIButton和UIImageView都是零,我似乎无法找出原因。 当我尝试调试它并打印每个视图的描述时,我得到的是 UIImageView(超出范围)
我一直在阅读,观看有关选项的视频,我理解如何在简单的情况下使用它,但这似乎有点复杂。
答案 0 :(得分:1)
您正在创建标签,按钮和图像视图。所以你的代码应该如下所示。我假设标签,Button和imageview是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)
}