How can I have a UIBarButtonItem with both image and text?

前端 未结 6 1217
[愿得一人]
[愿得一人] 2020-11-29 05:17

When I try to use an image for a UIBarButtonItem, the text isn\'t shown. Is there a way to show both the text and the image?

6条回答
  •  Happy的楠姐
    2020-11-29 05:40

    Swift 4.2 with target

    extension UIBarButtonItem {
        convenience init(image :UIImage, title :String, target: Any?, action: Selector?) {
            let button = UIButton(type: .custom)
            button.setImage(image, for: .normal)
            button.setTitle(title, for: .normal)
            button.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    
            if let target = target, let action = action {
                button.addTarget(target, action: action, for: .touchUpInside)
            }
    
            self.init(customView: button)
        }
    }
    

提交回复
热议问题