我主要在Storyboard中设计了布局。但是现在我想删除/隐藏UIButton(故事板),然后以编程方式添加UIImageView。
我设法以编程方式隐藏UIButton,但很难在UIStackView中正确显示UIImageView。
UIStackView已包含在Storyboard中设计的UIView。我需要以编程方式在这个水平UIStackView中将UIImageView添加到UIView的右侧。
任何提示?
import UIKit
import Firebase
import Photos
import Kingfisher
class editProfileVC: UIViewController {
var userArray = [User]()
// StackView outlets needed to set background color
@IBOutlet weak var backgroundStackView: UIStackView!
// Normal outlets
@IBOutlet weak var firstName: UITextField! // required
@IBOutlet weak var lastName: UITextField! // required - type of hunt
@IBOutlet weak var email: UITextField! // required - weapon name
@IBOutlet weak var city: UITextField! // optional (eg. 1)
@IBOutlet weak var country: UITextField! // optional (eg. 2)
@IBOutlet weak var primaryHunt: UITextField! // optional short description of the hunt
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var addImageBtn: UIButton!
@IBOutlet weak var addImageStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
if Auth.auth().currentUser == nil {
let authVC = self.storyboard?.instantiateViewController(withIdentifier: "authVC") as? authVC
self.present(authVC!, animated: true, completion: nil)
}
pinBackground(backgroundView, to: backgroundStackView)
// Get userdata from Firebase
let userId = (Auth.auth().currentUser?.uid)!
DataService.instance.getUserdata(userId: userId) { (returnedUserArray) in
if returnedUserArray.isEmpty == false {
// if user exist populate textfields with information from database
self.firstName.text = returnedUserArray[0].firstName
self.lastName.text = returnedUserArray[0].lastName
self.city.text = returnedUserArray[0].city
self.country.text = returnedUserArray[0].country
self.primaryHunt.text = returnedUserArray[0].defaultHunt
if returnedUserArray[0].profileImageURL.isEmpty == false {
// hide addImageBtn
self.addImageBtn.isHidden = true
// show profile image
let imageView = UIImageView()
imageView.kf.setImage(with: URL.init(string:returnedUserArray[0].profileImageURL))
self.addImageStackView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
}
}
}
}
}
UIStackView是绿色栏下面的顶部。灰色配置文件图标中的addImageBtn,文本为“添加配置文件图像”。
答案 0 :(得分:1)
要将任何视图添加到UIStackView,请执行以下操作:
stackView.addArrangedSubview(view)
如果要在特定位置添加视图,请执行以下操作:
stackView.insertArrangedSubview(view, at: 1) // Be careful you get the index correct.
如果你需要删除你执行此操作的视图:
stackView.removeArrangedSubview(view)
view.removeFromSuperview() // This is needed because the view still remains a sub view of the UIStackView.
它的外观取决于你如何设置堆栈视图。