[英]iOS custom back button - remove text and use custom image
我正在嘗試在我的應用中實現自定義后退按鈕。 我不希望有“后退”標題,也不需要任何先前的VC標題。 相反,我只是希望它看起來像所有VC的附件圖像。
我試過在UIBarButtonItem的外觀代理上使用setBackButtonBackgroundImage來替換圖像,但是它仍顯示“后退”標簽,我不確定如何擺脫它。
是否有人對實現此最佳實踐有任何建議? 我是否需要某種UINavigationController子類? 還是我仍然需要使用過去見過人們使用過的自定義返回方法路線來設置setLeftBarButtonItem(似乎很hacky)? 任何幫助將不勝感激。
嘗試將UIButton作為子視圖放在帶操作和所需圖像的leftBarButtonItem中的子視圖中,一切都會好起來的:)(您可能需要對其進行一些編輯,但這不應該對科學有所幫助:P)
在我的許多項目中,我都使用了一個自定義的后退按鈕,該按鈕只是一個沒有文本的圖標。 我做了一些嘗試以找到最佳方法,並提出了以下方法(我並不是說它是最佳方法,也不是唯一方法,但是它對我有用,而且很穩定)。
我的想法是實現一個Root ViewController來重新設置標准后退按鈕的樣式。 事實證明,這根本不容易。 經過大約1天的不同選擇擺弄,我終於找到了一個可行的解決方案。
訣竅是要有足夠大的透明背景(更大的然后是實際的人字形,否則將其調整為較小的尺寸),然后為人字形使用自定義圖像。
它可以工作,但是如您在下面的測量中所見,它有一個小的缺點:左側還有14個間隙。 如果要在右側匹配按鈕,則需要用14點來補償(是的,所以它的點數在視網膜上是28像素...)
這是我的代碼:
//this vc implements a custom back button, you can make this a root controller
//from which you inherit all your view controllers. But for simplicity reasons for this explanation
//I skipped this
class VCRoot: UIViewController {
override func viewDidLoad() {
//call supers
super.viewDidLoad()
//create custom back item
let backItem = UIBarButtonItem()
//as image set the back chevron icon its a 22x22 points (so 44x44 in retina)
backItem.image=PaintCode.imageOfBarBtnBack
let b = PaintCode.imageOfBarBtnBackgroundEmpty
//as background I use a 1 = 33 points (so 2x66 retina) fully transparant image
backItem.setBackButtonBackgroundImage(b, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
//set the newly created barbuttonitme as the back button
navigationItem.backBarButtonItem=backItem
}
}
//this vc puts a "forwards" button in the navbar on the right with a matching arrow
//The image of this matching forward arrow is the correct size (width!) so that its the same
//distance from the edge of the screen as the back button
class VC2: UIViewController {
//outlet to the barbutton item from IB
@IBOutlet weak var barbtn: UIBarButtonItem!
override func viewDidLoad() {
//call supers
super.viewDidLoad()
//the forward chevron in the image is shifted 14 points (so 28 retina) to the left
//so it has same distance from edge => its (22+14) x 22 = 36 x 22 points (72 x 44 retina)
barbtn.image=PaintCode.imageOfBarBtnForward
}
}
您也可以在這里參考我的博客: http : //www.hixfield.net/blog/2015/05/adding-a-custom-back-button-the-standard-way/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.