我創建了一個自定義視圖,並將uiimageview作爲子視圖。然後,我在導航欄中使用該自定義視圖作爲rightBarButtonItem。這可以在適當的位置顯示正確的圖標,但是無論出於什麼原因,我在「action」中定義的函數都不會被調用,所以當我點擊右邊的BarButtonItem時不會執行segue。奇怪的是,如果我不插入一個自定義視圖,而是將其評論一下,併爲rightItem設置一個標題,目標和動作,那麼該函數就可以正確執行。以某種方式添加自定義視圖與目標和動作屬性,但我似乎無法弄清楚如何解決它。任何幫助將不勝感激!IOS - Swift - 將目標和操作添加到BarButtonItem的自定義視圖
//create custom view for right item and set it
var imageViewRight:UIImageView = UIImageView()
imageViewRight.frame = CGRectMake(5, 10, 35, 25)
let rightImage:UIImage = UIImage(named: "cameraIconInactive")!
imageViewRight.image = rightImage
var rightView:UIView = UIView()
rightView.frame = CGRectMake(0, 0, 45, 45)
rightView.addSubview(imageViewRight)
var rightItem:UIBarButtonItem = UIBarButtonItem()
//this line right below is the problem - if I comment it out and replace with a simple rightItem.title = "test" and leave everything else the same, then the method runs properly
rightItem.customView = rightView
rightItem.target = self
rightItem.action = "pushProfileToCamera"
self.navigationItem.rightBarButtonItem = rightItem
}
func pushProfileToCamera(){
println("pushing profile to camera")
self.performSegueWithIdentifier("pushProfileToCamera", sender: nil)
}
編輯:
居然坐在這24小時,用此溶液來之前我看到了這些答案建議..任何理由我不應該這樣做呢?它的工作原理..
//create the custom rightBarButtonItem
//create the imageView with icon
var imageViewRight:UIImageView = UIImageView()
imageViewRight.frame = CGRectMake(5, 10, 35, 25)
var rightImage:UIImage = UIImage(named: "cameraIconInactive")!
imageViewRight.image = rightImage
//put the imageView inside a uiview
var rightView:UIView = UIView()
rightView.frame = CGRectMake(0, 0, 45, 45)
rightView.addSubview(imageViewRight)
//create the tap gesture recognizer for that uiview
var rightGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "pushProfileToCamera")
rightView.addGestureRecognizer(rightGestureRecognizer)
//create the uibarbuttonitem, assign our custom view to it, and insert it in the nav bar!
var rightItem:UIBarButtonItem = UIBarButtonItem()
rightItem.customView = rightView
self.navigationItem.rightBarButtonItem = rightItem