0

如下图所示,带有嵌入式 UITextView 的自定义控件将跳出它的界限。我尝试将剪辑应用于边界等无济于事。建立自定义控件时可能很简单。

这是 ViewController 的代码。结果如下

在此处输入图像描述

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var textStackView: UIStackView!
@IBOutlet weak var tabStackView: UIStackView!

override func viewDidLoad() {
    super.viewDidLoad()
    addButtons()
    addTextViews()
}

func addButtons(){
    var count = 0
    while (count <= 10){
        let btn = UIButton()
        btn.backgroundColor = UIColor.gray
        btn.setTitle("Btn \(count)", for: .normal)
        tabStackView.addArrangedSubview(btn)
        count += 1
    }
}

func addTextViews(){

    var count = 0
    while (count <= 5){

        if (count == 0){
            let textView = CustomView()
            textView.layer.borderColor = UIColor.green.cgColor //Green border
            textView.layer.borderWidth = 1
            textView.embededTextView.text = "Some sample text here. Some sample text here. Some sample text here. Some sample text here. Some sample text here."
            //textView.sizeToFit() //Does nothing
            //textView.clipsToBounds = true //Doesnt prevent overflow
            textStackView.addArrangedSubview(textView)
        }
        else{
            let textView = UITextView()
            textView.layer.borderColor = UIColor.black.cgColor
            textView.layer.borderWidth = 1
            textView.text = "Some sample text here. Some sample text here. Some sample text here. Some sample text here. Some sample text here."
            textStackView.addArrangedSubview(textView)
        }
        count += 1
    }
}
}

和自定义控件

import UIKit

class CustomView: UIView {

@IBOutlet var view: UIView!
@IBOutlet weak var embededTextView: UITextView!

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
    self.addSubview(self.view)
}

override init(frame: CGRect){
    super.init(frame: frame)
    Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
    self.addSubview(self.view)
    view.layer.borderWidth = 4
    view.layer.borderColor = UIColor.red.cgColor
    //view.sizeToFit()
}
}
4

1 回答 1

0

缺少的是 view.frame = self.bounds

override init(frame: CGRect){
    super.init(frame: frame)
    Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
    view.frame = self.bounds
    view.layer.borderWidth = 4
    view.layer.borderColor = UIColor.red.cgColor
    self.addSubview(self.view)
}
于 2017-03-13T09:40:59.357 回答