如何将UIButton添加到Swift Playground?

时间:2014-12-24 03:37:26

标签: swift swift-playground

所以我打开了游乐场,我只想添加一个简单的UIButton(或简单的UIView)进行测试。我无法显示它。这就是我到目前为止所做的:

import UIKit

var uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
uiButton.frame  = CGRectMake(0, 0, 100, 100)
uiButton.setTitle("Test", forState: UIControlState.Normal);
//self.view.addSubview(uiButton) <-- doesn't work

你们知道我做错了什么吗?感谢

4 个答案:

答案 0 :(得分:5)

我认为你可以在游乐场添加按钮,你的代码是正确的,当你点击快速查看时,你可以在这里看到你的按钮:

enter image description here

或者您可以点击“值历史记录:

”来查看该按钮

enter image description here

你不需要将其添加到视图中。

答案 1 :(得分:2)

如果你在游乐场import XCPlayground,你可以使用以下方式显示视图:

let view=UIView()
//other setup
XCPShowView("View Title",view)

这将在助理编辑器中显示视图

显示助理编辑器转到View > Assistant Editor > Show Assistant Editor

答案 2 :(得分:0)

import XCPlayground已被弃用,现在为import PlaygroundSupport。 您需要先创建视图并为其指定大小。

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) view.backgroundColor = UIColor.black

然后添加PlaygroundPage.current.liveView = view以便能够在助理编辑器中查看该视图。

现在您已经创建了视图,并且可以看到它的实时预览。您现在可以向其添加其他视图。在我的操场上,我添加了几个视图,因此我创建了一个具有默认宽度和高度的简单函数。

func addSquareView(x: Int, y: Int, width: Int = 100, height: Int = 100, color: UIColor) { let newView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) newView.backgroundColor = color view.addSubview(newView) }

addSquareView(x: 100, y: 100, color: .blue)

现在我的视野中心有一个蓝色方块。

答案 3 :(得分:0)

I was just doing my sorting programming and pated the code..it will help you to add a button in playgroud with target.

import UIKit
import PlaygroundSupport

let aButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
aButton.backgroundColor = .lightGray
aButton.setTitle("Run Sorting", for: .normal)
aButton.layer.cornerRadius = 10
aButton.clipsToBounds = true

class Sorting {
    
    @objc func callSorting() {
        self.getSortedArrayUsingSelectionSort()
    }
    
    func getSortedArrayUsingSelectionSort() {
        
        var arr = [4, 9, 10, 6, 1, 3]
        let n = arr.count
        
        for i in 0..<(n - 1) {
            var minIndex = i
            for j in (i+1)..<n {
                if arr[j] < arr[minIndex] {
                    minIndex = j
                }
            }
            if minIndex != i {
                let temp = arr[minIndex]
                arr[minIndex] = arr[i]
                arr[i] = temp
            }        }
        print(arr)
    }
  }

let target = Sorting()

aButton.addTarget(target, action: #selector(Sorting.callSorting), for: .touchUpInside)
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
containerView.backgroundColor = .white
PlaygroundPage.current.liveView = containerView

containerView.addSubview(aButton)