根据下图,带有嵌入式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()
}
}
答案 0 :(得分:0)
缺少的是 view.frame = self.bounds
in
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)
}