【问题标题】:Dynamic corner radius for a UITextViewUITextView 的动态角半径
【发布时间】:2017-05-26 22:34:39
【问题描述】:

我正在尝试根据显示的行数使我的 uitextview 的角半径动态化。文本是从我的后端检索的,所以行数会有所不同......

在使用框架创建文本视图后,我尝试在 viewDidLoad 中设置角半径,但由于某种原因不起作用。由于某种原因,我假设它返回 0。

非常感谢任何帮助。

(为了简单起见,我剪掉了很多代码。所有内容都已正确添加到子视图中。所有内容均以编程方式添加 - 此处根本不使用情节提要。文本视图在角落之外按预期显示半径)

viewDidLoad 内部:

    questionOneTextBox.layer.cornerRadius = self.questionOneTextBox.frame.height * 0.5
    questionTwoTextBox.layer.cornerRadius = self.questionTwoTextBox.frame.height * 0.5

【问题讨论】:

  • 您是说以编程方式添加UITextField,而不是使用情节提要?

标签: ios swift swift3 cornerradius


【解决方案1】:

如果您使用约束以编程方式创建文本视图,则需要调用self.questionOneTextBox.layoutIfNeeded()self.questionTwoTextBox.layoutIfNeeded()。这将初始化边界。

class ViewController: UIViewController {

    var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create the Text View

        self.textView = UITextView()

        self.textView.text = "This text will appear in the text view."

        self.textView.backgroundColor = .lightGray

        self.view.addSubview(self.textView)

        // Set the constraints

        self.textView.translatesAutoresizingMaskIntoConstraints = false

        self.textView.widthAnchor.constraint(equalToConstant: 280).isActive = true

        self.textView.heightAnchor.constraint(equalToConstant: 60).isActive = true

        self.textView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 60).isActive = true

        self.textView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

        // This will initialise the bounds

        self.textView.layoutIfNeeded()

        // Now the this should work

        self.textView.layer.cornerRadius = self.textView.frame.height * 0.5
    }
}

这就是这段代码的样子。

【讨论】:

    【解决方案2】:

    在调用viewDidLoad 时,视图没有布局(大小)。将您的圆角半径尺寸调整到 viewDidLayoutSubviewsviewWillAppear,此时尺寸已发生。

    【讨论】:

      【解决方案3】:

      您是否将clipsToBounds 设置为true?这可能会导致您的问题。我希望这会有所帮助

      【讨论】:

      • 我在回答时测试过,不需要它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2015-06-03
      • 2016-03-28
      相关资源
      最近更新 更多