如何以编程方式快速调整视图大小?

时间:2020-03-06 06:21:36

标签: ios swift uiview

我正在尝试在视图控制器中调整视图的大小。按下按钮时,视图的默认值为60。i更改视图的高度。当我在调试器模式下检查它时,它会显示新值的高度,但是经过几行或其他功能后,它会自动设置回默认值60。

@IBAction func confirmButtonWasPressed(_ sender: Any) {
    if confirmButton.titleLabel?.text == "Confirm pickup location" {
        if !(pickupLocationField.text?.isEmpty ?? false) && originLocation != nil {
            let frame = CGRect(x: searchesShadowView.frame.origin.x, y: searchesShadowView.frame.origin.y, width: searchesShadowView.frame.width, height: 115)

            self.searchesShadowView.frame = frame

            var imageView = UIImageView();
            var image = UIImage(named: "work25");
            imageView.image = image;
            dropoffLocationField.rightView = imageView;
            dropoffLocationField.rightViewMode = UITextField.ViewMode.always
        }
        else {
            showToast(with: "Select pick up location")
        }
    }
}

我使用的另一种方式

@IBAction func confirmButtonWasPressed(_ sender: Any) {
    if confirmButton.titleLabel?.text == "Confirm pickup location" {
        if !(pickupLocationField.text?.isEmpty ?? false) && originLocation != nil {
            searchesShadowView.frame.size.height = 115
            var imageView = UIImageView();
            var image = UIImage(named: "work25");
            imageView.image = image;
            dropoffLocationField.rightView = imageView;
            dropoffLocationField.rightViewMode = UITextField.ViewMode.always
        }
        else {
            showToast(with: "Select pick up location")
        }
    }
}

searchesShadowView.heightAnchor.constraint(equalToConstant: 115).isActive = true

4 个答案:

答案 0 :(得分:1)

您需要限制searchShadowView的高度。

Image Outlet

[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket core library initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer (theme-uilightness)
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

junit.framework.AssertionFailedError: classes not the same, expected 'class com.mycompany.SuccessPage', current 'class com.mycompany.HomePage'

    at org.apache.wicket.util.tester.WicketTester.assertResult(WicketTester.java:798)
    at org.apache.wicket.util.tester.WicketTester.assertRenderedPage(WicketTester.java:697)
    at com.mycompany.TestHomePage.validLogin(TestHomePage.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

答案 1 :(得分:0)

首先您应该从IBOutlet连接高度约束的Interface Builder,然后可以像这样->

更改高度约束的constant
@IBAction func confirmButtonWasPressed(_ sender: Any) {
    if confirmButton.titleLabel?.text == "Confirm pickup location" {

        if !(pickupLocationField.text?.isEmpty ?? false) && originLocation != nil {

        // You can change the value of the constraint
        searchesShadowHeightConstraint.constant = 115

        var imageView = UIImageView()
        var image = UIImage(named: "work25")
        imageView.image = image
        dropoffLocationField.rightView = imageView
        dropoffLocationField.rightViewMode = .always

    } else {
        showToast(with: "Select pick up location")
    }
    // Then you should update the layout
    view.layoutIfNeeded()
}

答案 2 :(得分:0)

您必须创建searchShadowView的高度限制的IBOutlet。

 searchViewheightConstaints.constant = yourRequiredHeight

///如果您是使用代码创建的,则

searchesShadowView.translatesAutoresizingMaskIntoConstraints = false

答案 3 :(得分:0)

尝试以下代码。

import UIKit

class MyViewController: UIViewController {
    let searchesShadowView = UIView()
    let plusButton = UIButton()
    let minusButton = UIButton()
    var heightLayoutConstraint:NSLayoutConstraint?
    let value: CGFloat = 10.0

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    init() {
        super.init(nibName: nil, bundle: nil)
        self.view.backgroundColor = .yellow
        loadUIView()
        loadPlusButton(plusButton)
        loadMinusButton(minusButton)
    }

    func loadUIView()  {
        self.view.addSubview(searchesShadowView)
        searchesShadowView.backgroundColor = .red
        searchesShadowView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint(item: searchesShadowView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 200).isActive = true
        NSLayoutConstraint(item: searchesShadowView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50).isActive = true
        NSLayoutConstraint(item: searchesShadowView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -50).isActive = true
        heightLayoutConstraint = NSLayoutConstraint(item: searchesShadowView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200)
        heightLayoutConstraint?.isActive = true
    }

    func loadPlusButton(_ button: UIButton) {
        self.view.addSubview(button)
        button.tag = 1
        button.backgroundColor = UIColor.green
        button.setTitle("+", for: .normal)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 100).isActive = true
        NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50).isActive = true
        NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant:
            80).isActive = true
        NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
    }

    func loadMinusButton(_ button: UIButton) {
        self.view.addSubview(button)
        button.tag = 0
        button.backgroundColor = UIColor.green
        button.setTitle("-", for: .normal)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 100).isActive = true
        NSLayoutConstraint(item: button, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -50).isActive = true
        NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant:
            80).isActive = true
        NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
    }

    @objc func buttonAction(sender: UIButton!) {
        UIView.animate(withDuration: 0, delay: 0.2, options: UIView.AnimationOptions.curveEaseOut, animations: {
            if sender.tag == 1 {
                self.heightLayoutConstraint?.constant += self.value
            }else{
                self.heightLayoutConstraint?.constant -= ((self.heightLayoutConstraint?.constant ?? 0)-self.value) >= 0 ? self.value : 0
            }
            self.view.layoutIfNeeded()
        }) { (value) in }
    }
}