2016-03-02 105 views
4

我曾嘗試將圓形按鈕放在iOS的右側導航欄上,但不幸的是,當我使用按鈕背景時,它不會將圖像倒圓顯示方形背景圖像,但當我移除圖像並將背景顏色放在背景顏色的圓形按鈕上時。我試過 代碼:如何在右側導航欄上設置帶有背景圖像的圓形按鈕項目

 let button = UIButton() 
     button.frame = CGRectMake(0, 0, 40, 40) 
     button.layer.cornerRadius = 0.5 * button.bounds.size.width 
     button.setImage(self.myPic, forState: .Normal)    
     let barButton = UIBarButtonItem() 
     barButton.customView = button 
     self.navigationItem.rightBarButtonItem = barButton 

回答

8

嘗試使用此代碼.. 爲圓按鈕,圖像 -

let button = UIButton() 
button.frame = CGRectMake(0, 0, 40, 40) 
let color = UIColor(patternImage: UIImage(named: "btnImage")!) 
button.backgroundColor = color 
button.layer.cornerRadius = 0.5 * button.bounds.size.width 
let barButton = UIBarButtonItem() 
barButton.customView = button 
self.navigationItem.rightBarButtonItem = barButton 

實際圖像---

let button = UIButton() 
    button.frame = CGRectMake(0, 0, 40, 40) 

    let image = UIImage(named: "btnImage")! 

    UIGraphicsBeginImageContextWithOptions(button.frame.size, false, image.scale) 
    let rect = CGRectMake(0, 0, button.frame.size.width, button.frame.size.height) 
    UIBezierPath(roundedRect: rect, cornerRadius: rect.width/2).addClip() 
    image.drawInRect(rect) 

    let newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 


    let color = UIColor(patternImage: newImage) 
    button.backgroundColor = color 
    button.layer.cornerRadius = 0.5 * button.bounds.size.width 
    let barButton = UIBarButtonItem() 
    barButton.customView = button 
    self.navigationItem.rightBarButtonItem = barButton 
+0

基本上你應該創建一個圖像的顏色來設置,然後設置按鈕的背景顏色 –

+0

它的工作原理,但這也裁剪圖像。我不想裁剪我的圖像 –

+0

我有這個解決方案。我編輯了我的答案..如果這或我早期的解決方案解決您的問題,請檢查此答案。 –

1

迅速2 設置欄中的圓形按鈕

func setProfileImageOnBarButton() { 

    let button = UIButton() 
    button.setImage(profileImage, forState: UIControlState.Normal) 
    button.addTarget(self, action:#selector(self.openUserProfile), forControlEvents: UIControlEvents.TouchUpInside) 
    button.frame = CGRectMake(0, 0, 36, 36) 
    button.layer.cornerRadius = CGRectGetWidth(button.frame)/2 
    button.layer.masksToBounds = true 
    let barButton = UIBarButtonItem(customView: button) 
    self.navigationItem.rightBarButtonItem = barButton 

} 
+0

CGRectMake在swift 3中不存在。 –

+0

它只是在swift3上的CGRect –

相關問題