【问题标题】:Change UIView frame Height and width from user input from UIText field从 UIText 字段的用户输入更改 UIView 框架的高度和宽度
【发布时间】:2018-05-18 11:54:00
【问题描述】:

我可以通过硬编码高度和宽度来更改按钮单击时 UIView 框架的高度和宽度,但是当我在 CGFloat 格式的 UItext 字段中从用户那里获得输入时,我无法更改它。

`

 import UIKit

  class SetBorderSizeViewController: UIViewController{

@IBOutlet weak var WidthText: UITextField!
@IBOutlet weak var Height: UITextField!
@IBOutlet weak var View_border: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    View_border.isHidden = true
}


   //Change UIView Height and width frame  on  "ChangeSizeButton" Button Press.....

@IBAction func ChangeSizeButton(_ sender: Any) {
     View_border.isHidden = false
    View_border.layer.borderWidth = 5
 /// Here i want to get user input from text field...
    View_border.frame.size.height = 20
    View_border.frame.size.width = 80
   }

   }

`

这里的任何人都可以根据我的要求更新我的代码吗???。

【问题讨论】:

    标签: ios xcode9.2 cgfloat swift4.1


    【解决方案1】:

    这段代码也可以:

    class ViewController: UIViewController {
    
        // MARK: IBOutlets
    
        @IBOutlet private weak var resizableView: UIView!
        @IBOutlet private weak var widthTextField: UITextField!
        @IBOutlet private weak var heightTextField: UITextField!
    
        // MARK: IBActions
    
        @IBAction private func didResizeButtonTapped(_ sender: UIButton) {
            let (newWidth, newHeight) = convertValues()
            resizableView.frame.size.width = newWidth
            resizableView.frame.size.height = newHeight
        }
    
    }
    
    // MARK: Private Methods
    
    private extension ViewController {
    
        func convertValues() -> (width: CGFloat, height: CGFloat) {
            let width = Float(widthTextField.text ?? "0")
            let height = Float(heightTextField.text ?? "0")
            return (CGFloat(width ?? 0.0), CGFloat(height ?? 0.0))
        }
    
    }
    

    但在我的情况下,我对“resizableView”使用了约束,因此我的视图每次都无效。在这种情况下,您可以为宽度和高度约束创建参考并将它们设置为新值,例如:

    widthConstraint.constant = <your_value>
    

    【讨论】:

      【解决方案2】:

      试试这个:

      @IBAction func ChangeSizeButton(_ sender: Any) {
               View_border.isHidden = false
              View_border.layer.borderWidth = 5
           /// Here i want to get user input from text field...
              View_border.frame.size.height = CGFloat(Float(WidthText.text!)!)
              View_border.frame.size.width = CGFloat(Float(Height.text!)!)
              self.View_border.layoutIfNeeded()
             }
      

      【讨论】:

      • 无法使用“(字符串?)”类型的参数列表为“Int”类型调用初始化程序 @Shabbir Ahmad
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2013-12-21
      • 2016-01-27
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多