ios - 在 UIButton 中使用 UIBarButtonItem 图标

标签 ios cocoa-touch uibutton uibarbuttonitemstyle

UIBarButtonItem 有多个可用图标。是否可以使用将其标识符设置为“垃圾桶”后出现的图标:

trash icon

UIButton?没有像设置identifierstyle 那样直接的方法来做到这一点。

最佳答案

iOS 13 支持 SF Symbols现在
UIImage(systemName: "trash")


对于 swift 4.2 (在主线程上调用)

extension UIBarButtonItem.SystemItem {
    func image() -> UIImage? {
        let tempItem = UIBarButtonItem(barButtonSystemItem: self,
                                       target: nil,
                                       action: nil)

        // add to toolbar and render it
        let bar = UIToolbar()
        bar.setItems([tempItem],
                     animated: false)
        bar.snapshotView(afterScreenUpdates: true)

        // got image from real uibutton
        let itemView = tempItem.value(forKey: "view") as! UIView
        for view in itemView.subviews {
            if let button = view as? UIButton,
                let image = button.imageView?.image {
                return image.withRenderingMode(.alwaysTemplate)
            }
        }

        return nil
    }
}

UIBarButtonSystemItem.play.image()

对于 Objective-C:

+ (UIImage *)imageFromSystemBarButton:(UIBarButtonSystemItem)systemItem {
    UIBarButtonItem* tempItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem target:nil action:nil];

    // Add to toolbar and render it
    UIToolbar *bar = [[UIToolbar alloc] init];
    [bar setItems:@[tempItem] animated:NO];
    [bar snapshotViewAfterScreenUpdates:YES];

    // Get image from real UIButton
    UIView *itemView = [(id)tempItem view];
    for (UIView* view in itemView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            return [(UIButton*)view imageForState:UIControlStateNormal];
        }
    }

    return nil;
}

关于ios - 在 UIButton 中使用 UIBarButtonItem 图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21187885/

相关文章:

javascript - "Run JavaScript on Web Page"的 iOS 12 快捷方式设置问题

ios - 如何让 UITableView 向上滚动以容纳键盘?

iphone - 当我触摸tableview内部的按钮时,它会自动转到TabGesture方法,但是我想要按钮触摸方法?

ios - BoundingRectWithSize - 选择使用的字体和字体大小

ios - 单击搜索时如何更新 tableView 的框架并隐藏段控件

ios - 更改 UITableViewRowAction 中的单元格背景颜色

ios - 在 UITextView 中捕获滚动 Action

xcode - 如何在嵌入式框架中使用 Cocoapods?

ios - 如何正确继承 UITableViewController

ios - 如何在 Swift 中创建具有自定义形状的 UIButton?