我正在努力找到一种让鼠标移动更顺畅的好方法,然后只是“翘曲”#34;周围。我以前使用this code in C#,所以我想我可以把它转换成Swift。这是我到目前为止所得到的,但是一旦我点击按钮,应用就会崩溃。出了什么问题?
@IBAction func btnMove(_ sender: Any) {
var test: NSPoint = NSMakePoint(200, 150)
LinearMovement(newPosition: test)
}
func LinearMovement(newPosition: NSPoint) {
let n = Int(readLine()!)!
var start: NSPoint! = NSMakePoint(self.mouseLocation.x, self.mouseLocation.y)
var iterPoint: NSPoint! = start
var slope: NSPoint! = NSPoint(x: newPosition.x - start.x, y: newPosition.y - start.y)
// Convert CGFloat to Int
var myIntValuex:Int = Int(slope.x)
var myIntValuey:Int = Int(slope.y)
// Devide by the number of steps
var slopex = myIntValuex / n
var slopey = myIntValuey / n
// Move the mouse to each iterative point.
for i in 0 ..< n {
var intIterx:Int = Int(iterPoint.x)
var intItery:Int = Int(iterPoint.y)
var iterPointx = intIterx + slopex
var iterPointy = intItery + slopey
var iterPointf: NSPoint = NSPoint(x: iterPointx, y: iterPointy)
CGWarpMouseCursorPosition(iterPointf)
// Thread.Sleep(MouseEventDelayMS) ??????
}
CGWarpMouseCursorPosition(newPosition)
}
答案 0 :(得分:1)
根据控制台消息,您看起来readLine()
或Int(readLine()!)
返回nil。如果你强行展开一个可选值并且值为零,那么你的应用就会崩溃。
如果您绝对100%确定您展开的价值永远不会为零,则只需要强制解包!
要避免这些类型的崩溃,请使用if let
或guard let
语句展开:
guard let line = readLine() else {
// handle the error appropriately here
// readLine() may return nil if STDIN was closed
print("Could not read line")
return
}
guard let n = Int(line) else {
// handle the error appropriately here
// Int(line) returns nil if line is not a valid Integer string
print("Expected an Int value")
return // or whatever fits here
}
您可以 - 通过一些修改 - 在循环中执行此操作,因此如果用户输入无效值,他可以再试一次。
答案 1 :(得分:0)
回到此位置后,我解决了这个问题。问题是readLine()
没有任何输入。现在,我将其替换为Int,称为steps
,并提供输入。 (从光标的开始位置到光标的最终位置之间的多少步。
要翻转y轴以正确读取所有位置点:
var start = NSPoint(x: 0, y: 0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let screenheight = NSScreen.main?.frame.height
NSEvent.addLocalMonitorForEvents(matching: .mouseMoved)
{
self.start = NSEvent.mouseLocation
self.start.y = screenheight! - self.start.y
print(self.start)
return $0
}
函数本身:
func LinearMovement(newPosition: NSPoint, steps: Int) {
var iterPoint: NSPoint = start
var slope: NSPoint = NSPoint(x: newPosition.x - start.x, y: newPosition.y - start.y)
// Divide by the number of steps
slope.x = slope.x / CGFloat(steps)
print(slope.x)
slope.y = slope.y / CGFloat(steps)
print(slope.y)
// Move the mouse to each iterative point.
for i in 0 ..< steps
{
let randomtime = Int.random(in: 150..<300)
iterPoint = NSPoint(x: iterPoint.x + slope.x, y: iterPoint.y + slope.y)
print(randomtime)
CGWarpMouseCursorPosition(iterPoint)
do {
usleep(UInt32(randomtime))
}
}
// Move the mouse to the final destination.
CGWarpMouseCursorPosition(newPosition)
start = newPosition
print(start)
}
并调用该函数:
var newloc = CGPoint(x: 200 , y: 200)
LinearMovement(newPosition: newloc, steps: 1920)