LoginSignup
2
0

More than 5 years have passed since last update.

Swift:NSPopUpButtonに関する小ネタ

Posted at

はじめに

NSPopUpButtonをコードで生成してカスタマイズする際の小ネタの忘備録です.
意外と実装に手こずったので参考までに.

actionの紐付け方

senderを使ってうまいことやります.

var popUp: NSPopUpButton!

override func awakeFromNib() {
    super.awakeFromNib()
    popUp = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 60, height: 40))

    popUp.target = self
    popUp.action = #selector(selectPopUp(_:))
}

@objc func selectPopUp(_ sender: NSPopUpButton) {
    // sender.selectedTag() とか sender.numberOfItemsを使った処理
}

arrow positionの変え方

一度NSPopUpButtonCellにキャストしてから,arroPositionを変更します.

let popUp = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 60, height: 40))

if let cell = popUp.cell as? NSPopUpButtonCell {
    cell.arrowPosition = NSPopUpButton.ArrowPosition.arrowAtBottom
}

画像選択式ポップアップの作成例

例:色選択ポップアップ
var colorPopUp: NSPopUpButton!

override func awakeFromNib() {
    super.awakeFromNib()
    let colorPopUp = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 60, height: 40))
    colorPopUp.addItems(withTitles: ["", "", ""])
    for (index, item) in colorPopUp.itemArray.enumerated() {
        item.tag = index
        item.image = createColorImage(index)
    }
    colorPopUp.imagePosition = NSControl.ImagePosition.imageOnly
    // 角丸などやるとなお良し
    // colorPopUp.wantsLayer = true
    // colorPopUp.layer?.cornerRadius = 12
}

func createColorImage(_ num: Int) -> NSImage {
    let image = NSImage(size: NSSize(width: 28, height: 28))
    image.lockFocus()
    let rect = NSRect(origin: CGPoint.zero, size: CGSize(width: 28, height: 28))
    let path = NSBezierPath(roundedRect: rect, xRadius: 8, yRadius: 8)
    NSColor.色名.setFill() //numに基づいて色を決定
    path.fill()
    image.unlockFocus()
    return image
}

その他属性変更

// ベゼルスタイルの変更
popUp.bezelStyle = NSButton.BezelStyle.shadowlessSquare

// 外観モードの変更
popUp.appearance = NSAppearance(named: NSAppearance.Name.aqua)
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0