- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我的应用程序即将进入最后阶段,它显示实时公交车 map 。所以,基本上,我有一个计时器,它定期从提供公交车实时位置的 xml 表中获取公交车的纬度和经度。我能够设置 xml 解析器,为公交车的运动设置动画并为公交车设置自定义(箭头)图像。
但是,问题是,从多条总线的数组中,我只能得到一条总线进行轮换。查看 xml 数据,它始终是旋转的 xml 表中的第一条总线。早些时候,我什至无法旋转单辆公共(public)汽车,所以用户“Good Doug”帮助了我,我能够让它工作。你可以在这里看到帖子:Custom annotation image rotates only at the beginning of the Program (Swift- iOS) .我尝试通过为每条总线制作一个 MKAnnotationView 数组来使用相同的解决方案。我不确定这是否是正确的方法。如果有人能帮我解决这个问题,我会很高兴:)
首先,XML 表是这样的(在这个例子中,有两辆车,所以我们只需要跟踪其中的两辆车):
<body>
<vehicle id="3815" routeTag="connector" dirTag="loop" lat="44.98068" lon="-93.18071" secsSinceReport="3" predictable="true" heading="335" speedKmHr="12" passengerCount="16"/>
<vehicle id="3810" routeTag="connector" dirTag="loop" lat="44.97313" lon="-93.24041" secsSinceReport="3" predictable="true" heading="254" speedKmHr="62" passengerCount="1"/>
</body>
这是我实现的一个单独的 Bus 类(在 Bus.swift 文件中)。这可能需要一些改进。
class Bus : MKPointAnnotation, MKAnnotation {
var oldCoord : CLLocationCoordinate2D!
var addedToMap = false
init(coord: CLLocationCoordinate2D) {
self.oldCoord = coord
}
}
这是我的 ViewController.swift 中的代码-
var busArray: [Bus!] = [] //Array to hold custom defined "Bus" types (from Bus.swift file)
var busViewArray : [MKAnnotationView?] = [nil, nil] //Array to hold MKAnnotationView of each bus. We're assuming 2 buses are active in this case.
var vehicleCount = 0 // variable to hold the number of buses
var vehicleIndex = 0 // variable to check which bus the xml parser is currently on.
var trackingBusForTheVeryFirstTime = true
// My xml parser function:
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) {
if (elementName == "vehicle" ) {
let latitude = attributeDict["lat"]?.doubleValue // Get latitude of current bus
let longitude = attributeDict["lon"]?.doubleValue // Get longitude of current bus
let dir = attributeDict["heading"]?.doubleValue // Get direction of current bus
var currentCoord = CLLocationCoordinate2DMake(latitude!, longitude!) // Current coordinates of the bus
// Checking the buses for the VERY FIRST TIME. This is usually the start of the program
if (trackingBusForTheVeryFirstTime || vehicleCount == 0) {
let bus = Bus(coord: currentCoord)
self.busArray.append(bus) // Put current bus to the busArray
self.vehicleCount++
}
else { // UPDATE BUS Location. (Note: this is not the first time)
// If index exceeded count, that means number of buses changed, so we need to start over
if (self.vehicleIndex >= self.vehicleCount) {
self.trackingBusForTheVeryFirstTime = true
// Reset count and index for buses
self.vehicleCount = 0
self.vehicleIndex = 0
return
}
let oldCoord = busArray[vehicleIndex].oldCoord
if (oldCoord.latitude == latitude && oldCoord.longitude == longitude) {
// if oldCoordinates and current coordinates are the same, the bus hasn't moved. So do nothing.
return
}
else {
// Move and Rotate the bus:
UIView.animateWithDuration(0.5) {
self.busArray[self.vehicleIndex].coordinate = CLLocationCoordinate2DMake(latitude!, longitude!)
// if bus annotations have not been added to the map yet, add them:
if (self.busArray[self.vehicleIndex].addedToMap == false) {
self.map.addAnnotation(self.busArray[self.vehicleIndex])
self.busArray[self.vehicleIndex].addedToMap = true
return
}
if let pv = self.busViewArray[self.vehicleIndex] {
pv.transform = CGAffineTransformRotate(self.map.transform, CGFloat(self.degreesToRadians(dir!))) // Rotate bus
}
}
if (vehicleIndex < vehicleCount - 1)
self.vehicleIndex++
}
else {
self.vehicleIndex = 0
}
return
}
}
}
这是我实现的 viewForAnnotation
:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let reuseId = "pin\(self.vehicleIndex)"
busViewArray[self.vehicleIndex] = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if busViewArray[self.vehicleIndex] == nil {
self.busViewArray[self.vehicleIndex] = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
busViewArray[vehicleIndex]!.image = imageWithImage(UIImage(named:"arrow.png")!, scaledToSize: CGSize(width: 21.0, height: 21.0))
self.view.addSubview(busViewArray[self.vehicleIndex]!)
}
else {
busViewArray[self.vehicleIndex]!.annotation = annotation
}
return busViewArray[self.vehicleIndex]
}
我对我的 viewForAnnotation
实现表示怀疑。我也不确定是否可以使用 MKAnnotationView
数组。也许,我对注释 View 在 iOS 中的工作方式的理解是错误的。如果有人可以帮助我解决这个问题,我会很高兴,因为我已经坚持了一段时间。即使整体实现需要更改,我也很乐意尝试一下。这是问题的屏幕截图。
再次请注意,所有巴士都出现在正确的位置并平稳移动,但只有其中一辆真正旋转。提前致谢。
最佳答案
我认为解析代码直接操作注释 View 是不合适的。你不知道它们是否可见,它们是否已经被实例化等等。 map View 负责管理注释 View ,而不是你。
如果您需要维护总线和注释之间的交叉引用,请这样做,但不要维护对注释 View 的引用。您的应用程序与注释的交互应仅限于注释本身。因此,创建一个具有 angle
属性的注解子类。
class MyAnnotation : MKPointAnnotation {
@objc dynamic var angle: CGFloat = 0.0
}
然后您可以让注释 View 子类“观察”自定义注释子类,随着注释的角度
变化而旋转。例如,在 Swift 4 中:
class MyAnnotationView : MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
addAngleObserver()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addAngleObserver()
}
// Remember, since annotation views can be reused, if the annotation changes,
// remove the old annotation's observer, if any, and add new one's.
override var annotation: MKAnnotation? {
willSet { token = nil }
didSet { addAngleObserver() }
}
// add observer
var token: NSKeyValueObservation!
private func addAngleObserver() {
if let annotation = annotation as? MyAnnotation {
transform = CGAffineTransform(rotationAngle: annotation.angle)
token = annotation.observe(\.angle) { [weak self] annotation, _ in
UIView.animate(withDuration: 0.25) {
self?.transform = CGAffineTransform(rotationAngle: annotation.angle)
}
}
}
}
}
或者在 Swift 3 中:
private var angleObserverContext = 0
class MyAnnotationView : MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
addAngleObserver()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addAngleObserver()
}
// add observer
private func addAngleObserver() {
if let annotation = annotation as? MyAnnotation {
transform = CGAffineTransform(rotationAngle: annotation.angle)
annotation.addObserver(self, forKeyPath: #keyPath(MyAnnotation.angle), options: [.new, .old], context: &angleObserverContext)
}
}
// remove observer
private func removeAngleObserver() {
if let annotation = annotation as? MyAnnotation {
annotation.removeObserver(self, forKeyPath: #keyPath(MyAnnotation.angle))
}
}
// remember to remove observer when annotation view is deallocated
deinit {
removeAngleObserver()
}
// Remember, since annotation views can be reused, if the annotation changes,
// remove the old annotation's observer, if any, and add new one's.
override var annotation: MKAnnotation? {
willSet { removeAngleObserver() }
didSet { addAngleObserver() }
}
// Handle observation events for the annotation's `angle`, rotating as appropriate
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &angleObserverContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
UIView.animate(withDuration: 0.5) {
if let angleNew = change![.newKey] as? CGFloat {
self.transform = CGAffineTransform(rotationAngle: angleNew)
}
}
}
}
现在,您的应用程序可以维护对已添加到 map 的注释的引用,并设置它们的角度
,这将在 map View 中以适当的方式可视化表示。
还有一个使用它的快速而肮脏的例子:
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
var annotation = MyAnnotation()
private let reuseIdentifer = Bundle.main.bundleIdentifier! + ".annotation"
private lazy var manager: CLLocationManager = {
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
return manager
}()
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(MyAnnotationView.self, forAnnotationViewWithReuseIdentifier: reuseIdentifer)
manager.requestWhenInUseAuthorization()
manager.startUpdatingHeading()
manager.startUpdatingLocation()
mapView.addAnnotation(annotation)
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
return mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifer, for: annotation)
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last,
location.horizontalAccuracy >= 0 else {
return
}
annotation.coordinate = location.coordinate
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
guard newHeading.headingAccuracy >= 0 else { return }
annotation.angle = CGFloat(newHeading.trueHeading * .pi / 180)
}
}
参见 previous revision of this answer以 Swift 2 为例。
关于ios - 只有一个(自定义)注释从一组其他注释中旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33457226/
好的,所以我编辑了以下... 只需将以下内容放入我的 custom.css #rt-utility .rt-block {CODE HERE} 但是当我尝试改变... 与 #rt-sideslid
在表格 View 中,我有一个自定义单元格(在界面生成器中高度为 500)。在该单元格中,我有一个 Collection View ,我按 (10,10,10,10) 固定到边缘。但是在 tablev
对于我的无能,我很抱歉,但总的来说,我对 Cocoa、Swift 和面向对象编程还很陌生。我的主要来源是《Cocoa Programming for OS X》(第 5 版),以及 Apple 的充满
我正在使用 meta-tegra 为我的 NVIDIA Jetson Nano 构建自定义图像。我需要 PyTorch,但没有它的配方。我在设备上构建了 PyTorch,并将其打包到设备上的轮子中。现
在 jquery 中使用 $.POST 和 $.GET 时,有没有办法将自定义变量添加到 URL 并发送它们?我尝试了以下方法: $.ajax({type:"POST", url:"file.php?
Traefik 已经默认实现了很多中间件,可以满足大部分我们日常的需求,但是在实际工作中,用户仍然还是有自定义中间件的需求,为解决这个问题,官方推出了一个 Traefik Pilot[1] 的功
我想让我的 CustomTextInputLayout 将 Widget.MaterialComponents.TextInputLayout.OutlinedBox 作为默认样式,无需在 XML 中
我在 ~/.emacs 中有以下自定义函数: (defun xi-rgrep (term) (grep-compute-defaults) (interactive "sSearch Te
我有下表: 考虑到每个月的权重,我的目标是在 5 个月内分散 10,000 个单位。与 10,000 相邻的行是我最好的尝试(我在这上面花了几个小时)。黄色是我所追求的。 我试图用来计算的逻辑如下:计
我的表单中有一个字段,它是文件类型。当用户点击保存图标时,我想自然地将文件上传到服务器并将文件名保存在数据库中。我尝试通过回显文件名来测试它,但它似乎不起作用。另外,如何将文件名添加到数据库中?是在模
我有一个 python 脚本来发送电子邮件,它工作得很好,但问题是当我检查我的电子邮件收件箱时。 我希望该用户名是自定义用户名,而不是整个电子邮件地址。 最佳答案 发件人地址应该使用的格式是: You
我想减小 ggcorrplot 中标记的大小,并减少文本和绘图之间的空间。 library(ggcorrplot) data(mtcars) corr <- round(cor(mtcars), 1)
GTK+ noob 问题在这里: 是否可以自定义 GtkFileChooserButton 或 GtkFileChooserDialog 以删除“位置”部分(左侧)和顶部的“位置”输入框? 我实际上要
我正在尝试在主页上使用 ajax 在 magento 中使用 ajax 显示流行的产品列表,我可以为 5 或“N”个产品执行此操作,但我想要的是将分页工具栏与结果集一起添加. 这是我添加的以显示流行产
我正在尝试使用 PasswordResetForm 内置函数。 由于我想要自定义表单字段,因此我编写了自己的表单: class FpasswordForm(PasswordResetForm):
据我了解,新的 Angular 7 提供了拖放功能。我搜索了有关 DnD 的 Tree 组件,但没有找到与树相关的内容。 我在 Stackblitz 上找到的一个工作示例.对比drag'ndrop功能
我必须开发一个自定义选项卡控件并决定使用 WPF/XAML 创建它,因为我无论如何都打算学习它。完成后应该是这样的: 到目前为止,我取得了很好的进展,但还有两个问题: 只有第一个/最后一个标签项应该有
我要定制xtable用于导出到 LaTeX。我知道有些问题是关于 xtable在这里,但我找不到我要找的具体东西。 以下是我的表的外观示例: my.table <- data.frame(Specif
用ejs在这里显示日期 它给我结果 Tue Feb 02 2016 16:02:24 GMT+0530 (IST) 但是我需要表现为 19th January, 2016 如何在ejs中执行此操作?
我想问在 JavaFX 中使用自定义对象制作 ListView 的最佳方法,我想要一个每个项目如下所示的列表: 我搜了一下,发现大部分人都是用细胞工厂的方法来做的。有没有其他办法?例如使用客户 fxm
我是一名优秀的程序员,十分优秀!