私のアプリには、複数のナビゲーションコントローラとそのルートビューコントローラがあります。私は各ナビゲーションバーに、ソーシャルメディアのボタンをバーの右側に密接に配置させたいと思っています。同じ場合、このコードを使用して1つのビューコントローラーのボタンを表示しています:繰り返しコードを削除するSwift 3
let fbImage = UIImage(named: "Facebook.png")!
let twitterImage = UIImage(named: "Twitter.png")!
let youtbImage = UIImage(named:"YouTube.png")!
let fbBtn: UIButton = UIButton(type: .custom)
fbBtn.setImage(fbImage, for: UIControlState.normal)
fbBtn.addTarget(self, action: #selector(HomeViewController.fbBtnPressed), for: UIControlEvents.touchUpInside)
fbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let fbBarBtn = UIBarButtonItem(customView: fbBtn)
let twitterBtn: UIButton = UIButton(type: .custom)
twitterBtn.setImage(twitterImage, for: UIControlState.normal)
twitterBtn.addTarget(self, action: #selector(HomeViewController.twitterBtnPressed), for: UIControlEvents.touchUpInside)
twitterBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let twitterBarBtn = UIBarButtonItem(customView: twitterBtn)
let youtbBtn: UIButton = UIButton(type: .custom)
youtbBtn.setImage(youtbImage, for: UIControlState.normal)
youtbBtn.addTarget(self, action: #selector(HomeViewController.youtubeBtnPressed), for: UIControlEvents.touchUpInside)
youtbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let youtbBarBtn = UIBarButtonItem(customView: youtbBtn)
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
すべてのナビゲーションバーに同じボタンが必要です。このコードと各ターゲットメソッドをそれぞれのビューコントローラのviewDidLoad()
に簡単にコピーできますが、コードが多すぎます。だからこのような状況を避ける方法はありますか?
私はSwift 3を使用しています。私はiOSを初めて使用しています。どんな助けもありがとう!
のためにそれを作ってみますそのコードをその中に入れ、それぞれのViewControllerはCommonViewControllerから継承します。 – Larme