Swift:以编程方式将自动布局约束从一个视图复制到另一个视图

时间:2016-03-04 16:16:59

标签: swift

我有一个UIButton我在故事板中设置了自动布局约束。我还使用UIView UIViewController方法启动viewDidLoad。我使这个视图(几乎)具有与UIButton相同的所有属性,但是当我在模拟器中运行它时,它并没有"坚持"到按钮。这就是我所拥有的:

class ViewController: UIViewController {

    @IBOutlet weak var someButton: UIButton!

    func viewDidLoad() {
        super.viewDidLoad()

        let someView = UIView()
        someView.backgroundColor = UIColor.greenColor()
        someView.frame = someButton.bounds
        someView.frame.origin = someButton.frame.origin
        someView.autoresizingMask = someButton.autoresizingMask
        someView.autoresizesSubviews = true
        someView.layer.cornerRadius = someButton.layer.cornerRadius
        someView.clipsToBounds = true
        someView.userInteractionEnabled = false
        view.insertSubview(someView, belowSubview: someButton)
    }

}

我想我错过了someView。自动布局约束?

编辑:我认为访问UIButton的约束会起作用,但它们似乎是一个空数组。故事板的约束是隐藏的吗?

someView.addConstraints(someButton.constraints)

感谢。

1 个答案:

答案 0 :(得分:4)

复制那种方式的约束失败,因为:

  • 故事板中的约束被添加到超级视图而不是按钮本身
  • 您尝试复制的约束是引用按钮而不是新视图

不是复制约束,而是保持简单并创建新的约束并引用按钮:

$.ajax({


  type : 'POST',
  data : formula,
  url : 'http://10.0.0.119/melleve/statusorig2.php',
  success : function(data){


    var retorno = JSON.parse(data);




var testandoisso = $.map(retorno, function (value) {

  var latitude = value.latitude;
  var longitude = value.longitude;
  var id = value.idmoto;



var lat1 = -22.8650697;
var lat2 = latitude;

var long1 = -43.287510499999996;
var long2 = longitude;

var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = long1 - long2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1)*Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist);

dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;


var finaldist = dist * 1.609344;


return finaldist;


});

var ok = Math.min.apply(Math, testandoisso);

     console.log(ok);



  },
  error: function(jqXHR, textStatus, errorThrown){
    //debugger;
  }
  //,complete: function(jqXHR, textStatus){
   // debugger;
  //}

})