2015-06-30 2 views
0

Я нахожусь в цикле индекса и добавляю метки, основанные на каждом элементе индекса. Поскольку я программно добавляю эти ярлыки, я не знаю, как ограничить их в крайнем правом углу устройства. Ниже я объясняю, как я думаю, что ограничения работают. Моя цель = буксируемая пространство для надтаблицы (или содержащие вид) постоянный набор на 8.Быстрое программное добавление ограничений на метки

let y_align = 340 * index + 70 
let x_align = self.deviceWidth - 110 
var derp = UILabel(frame: CGRectMake(0, 0, 200, 21)) 
derp.center = CGPointMake(CGFloat(x_align), CGFloat(y_align))  
derp.textAlignment = NSTextAlignment.Right  
derp.text = json["things"][index]["thing"].string!  
self.some_view_container.addSubview(derp) 

//now this is what I understand about constraints  
let xconstraint = NSLayoutConstraint( 
    item: derp, //-- the object that we want to constrain  
    attribute: NSLayoutAttribute.Trailing, //-- the attribute of the object we want to constrain  
    relatedBy: NSLayoutRelation.Equal, //-- how we want to relate THIS object to A DIFF object  
    toItem: some_view_container, //-- this is the different object we want to constrain to  
    attribute: NSLayoutAttribute.Right, //-- the attribute of the different object  
    multiplier: 1, //-- multiplier  
    constant: 8 //-- regular constant  
) 

derp.addConstraint(xconstraint) 

это то, что я хочу в человеческих терминах

  • деталь: Я хочу, чтобы ограничить Derp, который является значение json
  • атрибут: я хочу ограничить его конечное пространство, чтобы оно полностью оттолкнуло его вправо
  • relatedBy: понятия не имею здесь, меня не волнует, связано ли это с чем-либо, потому что Я просто хочу, чтобы конечное пространство супер вид
  • toItem: Я хочу, чтобы подтолкнуть ее к правой части надтаблицы ИЛИ это контейнер, который является some_view_container
  • атрибут: ни одна идея здесь, я не забочусь об атрибуте вид контейнера
  • мультипликатора: I просто хотим, число константы так умножить на 1
  • константы: Я хочу, чтобы трейлинг пространство было 8 от края

ответ

3

Вы можете использовать этот код в качестве справки:

import UIKit 

class ViewController: UIViewController { 
override func viewDidLoad() { 
    super.viewDidLoad() 
    addLabels() 
} 

func addLabels(){ 
    let deviceWidth = UIScreen.mainScreen().bounds.width 
    //Here recopilate the constranins for later activation 
    var constraints = [NSLayoutConstraint]() 
    //Here I'm assuming that there are 5 labels 
    for index in 0..<5 { 
     //adjust this to spaciate labels 
     let y_align = CGFloat(20 * index + 70) 
     let x_align = deviceWidth - 110 
     var derp = UILabel(frame: CGRectMake(0, 0, 200, 21)) 
     derp.center = CGPointMake(CGFloat(x_align), CGFloat(y_align)) 
     derp.textAlignment = NSTextAlignment.Right 
     derp.text = "things \(index)" 

     let xconstraint = NSLayoutConstraint(
      item: derp, //-- the object that we want to constrain 
      attribute: NSLayoutAttribute.Trailing, //-- the attribute of the object we want to constrain 
      relatedBy: NSLayoutRelation.Equal, //-- how we want to relate THIS object to A DIFF object 
      toItem: self.view, //-- this is the different object we want to constrain to 
      attribute: NSLayoutAttribute.Right, //-- the attribute of the different object 
      multiplier: 1, //-- multiplier 
      constant: -8 //-- (Take a look here, its a minus) 
     ) 
     let yconstraint = NSLayoutConstraint(
      item: derp, //-- the object that we want to constrain 
      attribute: NSLayoutAttribute.Top, //-- the attribute of the object we want to constrain 
      relatedBy: NSLayoutRelation.Equal, //-- how we want to relate THIS object to A DIFF object 
      toItem: self.view, //-- this is the different object we want to constrain to 
      attribute: NSLayoutAttribute.TopMargin, //-- the attribute of the different object 
      multiplier: 1, //-- multiplier 
      constant: y_align //-- regular constant 
     ) 
     //recopilate constraints created here 
     constraints.append(xconstraint) 
     constraints.append(yconstraint) 
     derp.setTranslatesAutoresizingMaskIntoConstraints(false) 
     //add them to the desired control 
     self.view.addSubview(derp) 
    } 
    //This will tell iOS to use your constraint 
    NSLayoutConstraint.activateConstraints(constraints) 
} 
} 
+0

Благодарит так много! Ты мужчина, именно то, что я искал! –

1

для быстрых 3,0

func addLabels(){ 
    let deviceWidth = UIScreen.main.bounds.width 
    //Here recopilate the constranins for later activation 
    var constraints = [NSLayoutConstraint]() 
    //Here I'm assuming that there are 5 labels 
    for index in 0..<5 { 
     //adjust this to spaciate labels 
     let y_align = CGFloat(20 * index + 70) 
     let x_align = deviceWidth - 110 
     var derp = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) 
     derp.center = CGPoint(x:CGFloat(x_align), y:CGFloat(y_align)) 

     derp.textAlignment = NSTextAlignment.right 
     derp.text = "things \(index)" 

     let xconstraint = NSLayoutConstraint(
      item: derp, //-- the object that we want to constrain 
      attribute: NSLayoutAttribute.trailing, //-- the attribute of the object we want to constrain 
      relatedBy: NSLayoutRelation.equal, //-- how we want to relate THIS object to A DIFF object 
      toItem: self.view, //-- this is the different object we want to constrain to 
      attribute: NSLayoutAttribute.right, //-- the attribute of the different object 
      multiplier: 1, //-- multiplier 
      constant: -8 //-- (Take a look here, its a minus) 
     ) 
     let yconstraint = NSLayoutConstraint(
      item: derp, //-- the object that we want to constrain 
      attribute: NSLayoutAttribute.top, //-- the attribute of the object we want to constrain 
      relatedBy: NSLayoutRelation.equal, //-- how we want to relate THIS object to A DIFF object 
      toItem: self.view, //-- this is the different object we want to constrain to 
      attribute: NSLayoutAttribute.topMargin, //-- the attribute of the different object 
      multiplier: 1, //-- multiplier 
      constant: y_align //-- regular constant 
     ) 
     //recopilate constraints created here 
     constraints.append(xconstraint) 
     constraints.append(yconstraint) 
     derp.translatesAutoresizingMaskIntoConstraints = false 
     //add them to the desired control 
     self.view.addSubview(derp) 
    } 
    //This will tell iOS to use your constraint 
    NSLayoutConstraint.activate(constraints) 
} 
Смежные вопросы