ios - 将尝试通过打破约束来恢复 <NSLayoutConstraint :0x17008b130 UILabel

标签 ios swift uilabel nslayoutconstraint

我正在将我的 swift 应用程序连接到低功耗蓝牙外围设备。我是 Swift 的新手,我的问题完全与快速编码有关,而不是 BLE。

我监听外围设备以查看按钮是否被按下。我定义了一个标签并为其分配了一个文本。当应用检测到按下按钮时,我希望更改标签测试,但我的应用却崩溃了。

你可以在这里看到我的代码:

   import CoreBluetooth
import UIKit

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    var manager:CBCentralManager!
    var peripheral:CBPeripheral!
    @IBOutlet weak var statusLabel: UILabel!


    let BEAN_NAME = "Security Tag"
    let BEAN_SCRATCH_UUID = CBUUID(string: "00001C0F-D102-11E1-9B23-000EFB0000A7")
    let BEAN_SERVICE_UUID = CBUUID(string: "00001c00-d102-11e1-9b23-000efb0000a7")

    override func viewDidLoad() {
        super.viewDidLoad()
        manager = CBCentralManager(delegate: self, queue: nil)
    }

    func centralManagerDidUpdateState(_ central:CBCentralManager) {
        if central.state == CBManagerState.poweredOn {
            central.scanForPeripherals(withServices: nil, options: nil)
            debugPrint("Searching ...")
        } else {
            debugPrint("Bluetooth not available.")
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        let device = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? NSString

        if device?.contains(BEAN_NAME) == true {
            debugPrint("Found Bean.")

            self.manager.stopScan()
            self.peripheral = peripheral
            self.peripheral.delegate = self

            manager.connect(peripheral, options: nil)
        }
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        debugPrint("Getting services ...")
        peripheral.discoverServices(nil)
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service in peripheral.services! {
            let thisService = service as CBService

            debugPrint("Service: ", service.uuid)

            if service.uuid == BEAN_SERVICE_UUID {
                debugPrint("Using scratch.")
                peripheral.discoverCharacteristics(nil, for: thisService)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        debugPrint("Enabling ...")

        for characteristic in service.characteristics! {
            let thisCharacteristic = characteristic as CBCharacteristic

            debugPrint("Characteristic: ", thisCharacteristic.uuid)

            if thisCharacteristic.uuid == BEAN_SCRATCH_UUID {
                debugPrint("Set to notify: ", thisCharacteristic.uuid)

                // Prepare to show data

                self.peripheral.setNotifyValue(true, for: thisCharacteristic)
           }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if characteristic.uuid == BEAN_SCRATCH_UUID {
            let content = String(data: characteristic.value!, encoding: String.Encoding.utf8)

            debugPrint("Notified.")
            self.statusLabel.text = "Your Purchase is Registered."

        }
    }

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        debugPrint("Disconnected.")

        central.scanForPeripherals(withServices: nil, options: nil)

        // Hide respective user interface
    }

}

一行内容为:self.statusLabel.text =“您的购买已注册。”

是我得到异常的地方。

这是我得到的错误:

    2017-02-06 13:42:19.825869 kevinbletest[2143:695095] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x17008b130 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.width == 270   (active)>",
    "<NSLayoutConstraint:0x17008b770 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.centerX == UIView:0x11dd0c850.centerX   (active)>",
    "<NSLayoutConstraint:0x17008b7c0 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.leading == UIView:0x11dd0c850.leadingMargin + 50   (active)>",
    "<NSLayoutConstraint:0x17408c3f0 'UIView-Encapsulated-Layout-Width' UIView:0x11dd0c850.width == 375   (active)>"
)
    Will attempt to recover by breaking constraint 
    <NSLayoutConstraint:0x17008b130 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.width == 270   (active)>    
    Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
    The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
    fatal error: unexpectedly found nil while unwrapping an Optional value
    2017-02-06 13:42:25.299886 kevinbletest[2143:695095] fatal error: unexpectedly found nil while unwrapping an Optional value
    (lldb) 

最佳答案

根据我的阅读,错误在于:

<NSLayoutConstraint:0x17008b130 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.width == 270   (active)>

如果您在下面阅读它,似乎 NSLayout 试图将宽度为 270 的标签居中,但失败了,因为您的文本大于 270。

在下面它说你的应用程序崩溃是因为你的标签实际上是零。

尝试 printf(self.myLabel) 看看它是否为 nil。

如果您将标签添加到 Storyboard 中并在 viewDidAppear 完成之前按下按钮,您的标签可能为零。

也可以不受任何限制地尝试。只需删除约束。 + 等待 ViewController 加载(viewDidAppear),然后点击。

你的应用程序崩溃是因为它解包了一个 nil 的可选值,而不是因为约束。

关于ios - 将尝试通过打破约束来恢复 <NSLayoutConstraint :0x17008b130 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065307/

相关文章:

ios - Swift/菜单( View )随机导致 "Command failed due to signal: Segmentation fault: 11"

ios - 如何在 Swift 中将多个子进度聚合为一个主进度

ios - boundingRectWithSize 返回多行标签的错误高度值

swift - 如何修复 "Binary operator ' >' cannot be applied to two ' NSNumber' 操作数“错误

swift - RealmSwift 保存了多少数据?

ios - UILabel sizeToFit 不适用于自动布局 ios6

ios - UILabel 的字体颜色没有改变

ios - 在模拟器中注销 Appstore

ios - 在 xcode 中检测 iOS 版本 - 程序中出现意外的 '@'

ios - 防止 Tab Bar 切断 WKWebView 文本