简体   繁体   English

带有约束的iOS自定义UIControl,UITextView:无法同时满足约束

[英]iOS custom UIControl with constraints, UITextView: Unable to simultaneously satisfy constraints

I created a custom UITextView that does some syntax highlighting and it works very well. 我创建了一个自定义UITextView ,它可以突出显示一些语法,并且效果很好。 When I create a regular UITextView and add constraints, I get no errors or warnings. 创建常规UITextView并添加约束时,不会收到任何错误或警告。 When I use my custom UITextView (which inherits from UITextView ) I get all sorts of constraint warnings that say it can't satisfy the constraints I've added. 当我使用自定义的UITextView (继承自UITextView )时,会收到各种约束警告,说它不能满足我添加的约束。 For example: 例如:

(
    "<NSLayoutConstraint:0x7b9c8750 MyApp.MyCodeAppTextView:0x7c280200.width == UIView:0x7bc621c0.width>",
    "<NSAutoresizingMaskLayoutConstraint:0x7bc68be0 h=--& v=--& H:[MyApp.MyCodeAppTextView:0x7c280200(0)]>",
    "<NSLayoutConstraint:0x7bc6a720 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7bc621c0(320)]>"
)

Is there something I have to add to my custom UIControl/UITextView in order for it to be able to respond to constraints properly? 我必须添加一些自定义UIControl / UITextView才能使其正确响应约束吗?

Apparently you need to put these three things in your custom class. 显然,您需要将这三件事放在自定义类中。

  1. setTranslatesAutoresizingMaskIntoConstraints(false)
  2. intrinsicContentSize
  3. requiresConstraintBasedLayout

With that in mind this is the code I added to my custom class to make it work. 考虑到这一点,这是我添加到自定义类中以使其工作的代码。

import UIKit

public class YourCustomUIControl:UIView {
    required public init(coder aDecoder: NSCoder) {
        super.init()
        setTranslatesAutoresizingMaskIntoConstraints(false)
    }

    override public func intrinsicContentSize() -> CGSize {
        return CGSizeMake(100, 70)
    }

    override class public func requiresConstraintBasedLayout() -> Bool {
        return true
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM