简体   繁体   中英

Giving a regular button a bar button identifier in swift

I want to get a button which isn't a bar button item to display the trash bin icon. Does anybody know how to do this programmatically?

Add your action:

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

Then inside 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

If you need something to easily more around, here is a hacky solution that seems to work. If you need other features from UIButton , this won't be much good.

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]
    }
}

In your view controller:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM