0
我正在使用GitHub項目來重新創建iOS項目中Android中存在的「籌碼」組件。我想在斯威夫特寫這個Objective-C代碼:使用viewWithTag創建視圖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;
這是我到目前爲止所。
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(超出範圍)
我一直在閱讀,觀看視頻自選,我知道如何使用它進行簡單案件,但這似乎有點複雜。
就是這樣。順便說一下,Xcode給我錯誤的代碼,並建議添加一個?在創建imageview,標籤和按鈕後查看,如下所示:'if let label = view?.viewWithTag(2)as? UILabel'之後,它按預期工作。謝謝。 – Alex
對不起,我忘了更新.i更新了我的答案 – Vinodh