在swift中为常规按钮提供一个条形按钮标识符

时间:2015-06-28 06:49:29

标签: ios swift button icons uibarbuttonitem

我想要一个按钮,它不是一个条形按钮项目,用于显示垃圾桶图标。有人知道如何以编程方式执行此操作吗?

2 个答案:

答案 0 :(得分:0)

添加您的操作:

func buttonAction(sender:UIButton!)
{
    println("Button tapped") // add your button tapped logic here
}

然后在viewDidLoad:

    var image: UIImage = UIImage(named: "Icon")!  //Icon = your image name, no need for the extension
    let button   = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton  //UIButton type must be CUSTOM or you will get a plain blue system button
    button.frame = CGRectMake(100, 100, 100, 50)  // Size and Co-ordinates
    button.setImage(image, forState: .Normal)  //for normal non touched state 
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) // "buttonAction" received here

    self.view.addSubview(button)  //adds subview to display the button

答案 1 :(得分:0)

如果你需要更容易的东西,这里有一个似乎有用的hacky解决方案。如果您需要UIButton中的其他功能,这将不会太好。

BarButtonView.swift

import UIKit

class BarButtonView: UIView {

    var toolbar = UIToolbar()
    var toolbarFrame = CGRect() {
        didSet {
            display()
        }
    }

    var button = UIBarButtonItem() {
        didSet {
            display()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        toolbarFrame = frame
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func display() {
        toolbar = UIToolbar(frame: toolbarFrame)
        toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: .Default)
        toolbar.setShadowImage(UIImage(), forToolbarPosition: .Any)

        addSubview(toolbar)

        let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)

        toolbar.items = [space, button, space]
    }
}

在视图控制器中:

let button = BarButtonView(frame: CGRect(x: 10, y: 10, width: 40, height: 44))
button.button = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: nil)

view.addSubview(button)