Разрешить пользователю редактировать табличную метку таблицы при длительном нажатии [дубликат]

Я нашел это полезным:

получает членство в группе для Active Directory

И у меня есть этот рабочий код:

import java.util.Hashtable;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class TestAD1 {

    private static String userBase = "DC=SomeName,DC=SomeName,DC=SomeName,DC=SomeName,DC=COM,DC=US";

    public static void main(String[] args) {
        TestAD1 tad = new TestAD1();
        try {
            // Create a LDAP Context
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, "ldap.serviceaccount@domain.com");
            env.put(Context.SECURITY_CREDENTIALS, "drowssap");
            env.put(Context.PROVIDER_URL, "ldap://fully.qualified.server.name:389");
            LdapContext ctx = new InitialLdapContext(env, null);
            InitialDirContext inidircontext = new InitialDirContext(env);
            DirContext dirctx = new InitialLdapContext(env, null);
            System.out.println("Connection Successful.");

            // Print all attributes of the name in namespace
            SearchControls sctls = new SearchControls();
            String retatts[] = {"sn", "mail", "displayName", "sAMAccountName"};
            sctls.setReturningAttributes(retatts);
            sctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String srchfilter = "(&(objectClass=user)(mail=*))";
            String srchbase = userBase;
            int totalresults = 0;

            NamingEnumeration answer = dirctx.search(srchbase, srchfilter, sctls);
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
                totalresults++;
                System.out.println(">>>  " + sr.getName());

                Attributes attrs = sr.getAttributes();
                if (answer == null || !answer.hasMore()) {
                    System.out.println("No result found");
                    return;
                }

                if (attrs != null) {
                    try {
                        System.out.println("    surname: " + attrs.get("sn").get());
                        System.out.println("    Email - ID: " + attrs.get("mail").get());
                        System.out.println("    User - ID: " + attrs.get("displayName").get());
                        System.out.println("    Account Name: " + attrs.get("sAMAccountName").get());
                        tad.GetGroups(inidircontext, attrs.get("sAMAccountName").get().toString());
                    } catch (NullPointerException e) {
                        System.out.println("Error listing attributes..." + e);

                    }
                }
                System.out.println("Total Results : " + totalresults);
                // close dir context
                dirctx.close();
            }

            ctx.close();
        } catch (NamingException e) {
            System.out.println("Problem Search Active Directory..." + e);
            //e.printStackTrace();
        }

    }

    // Get all the groups.

    public void GetGroups(InitialDirContext context, String username) throws NamingException {
        String[] attrIdsToSearch = new String[]{"memberOf"};
        String SEARCH_BY_SAM_ACCOUNT_NAME = "(sAMAccountName=%s)";
        String filter = String.format(SEARCH_BY_SAM_ACCOUNT_NAME, username);
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setReturningAttributes(attrIdsToSearch);
        NamingEnumeration results = context.search(userBase, filter, constraints);
        // Fail if no entries found
        if (results == null || !results.hasMore()) {
            System.out.println("No result found");
            return;
        }
        SearchResult result = (SearchResult) results.next();
        Attributes attrs = result.getAttributes();
        Attribute attr = attrs.get(attrIdsToSearch[0]);

        NamingEnumeration e = attr.getAll();
        System.out.println(username + " is Member of the following groups  : \n");
        while (e.hasMore()) {
            String value = (String) e.next();
            System.out.println(value);
        }
    }

}

0
задан rmaddy 10 July 2016 в 15:18
поделиться

3 ответа

Если вы хотите сделать это целиком из кода:

import UIKit

struct MatchInfo {
    var teamA: String
    var teamB: String
}

class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var matches = [MatchInfo]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self

        // Add some data
        matches.append(MatchInfo(teamA: "Panthers", teamB: "Broncos"))
        matches.append(MatchInfo(teamA: "Bucaneers", teamB: "Falcons"))
        matches.append(MatchInfo(teamA: "Vikings", teamB: "Titans"))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    // MARK: -
    // MARK: Table View Data Source Delegate
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return matches.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell") ?? makeCell()

        let textFieldA = cell.viewWithTag(1) as! UITextField
        let textFieldB = cell.viewWithTag(2) as! UITextField

        let row = indexPath.row
        textFieldA.text = matches[row].teamA
        textFieldB.text = matches[row].teamB

        return cell
    }

    func makeCell() -> UITableViewCell {
        let textFieldA = UITextField(frame: CGRectZero)
        let textfieldB = UITextField(frame: CGRectZero)

        textFieldA.tag = 1
        textfieldB.tag = 2
        [textFieldA, textfieldB].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
            $0.borderStyle = .RoundedRect
        }

        let vsLabel = UILabel(frame: CGRectZero)
        vsLabel.text = "vs."
        vsLabel.translatesAutoresizingMaskIntoConstraints = false

        let cell = UITableViewCell(style: .Default, reuseIdentifier: "myCell")
        [textFieldA, textfieldB, vsLabel].forEach { cell.contentView.addSubview($0) }

        // Layout the elements
        let views = ["A": textFieldA, "B": textfieldB, "vs": vsLabel]
        let c1 = NSLayoutConstraint.constraintsWithVisualFormat("H:[A]-8-[vs]-8-[B]", options: .AlignAllBaseline, metrics: nil, views: views)
        let c2 = NSLayoutConstraint(item: textFieldA, attribute: .Left, relatedBy: .Equal, toItem: cell.layoutMarginsGuide, attribute: .Left, multiplier: 1, constant: 0)
        let c3 = NSLayoutConstraint(item: textfieldB, attribute: .Right, relatedBy: .Equal, toItem: cell, attribute: .Right, multiplier: 1, constant: 0)
        let c4 = NSLayoutConstraint(item: textFieldA, attribute: .CenterY, relatedBy: .Equal, toItem: cell.contentView, attribute: .CenterY, multiplier: 1, constant: 0)
        let c5 = NSLayoutConstraint(item: textFieldA, attribute: .Width, relatedBy: .Equal, toItem: textfieldB, attribute: .Width, multiplier: 1, constant: 0)

        NSLayoutConstraint.activateConstraints(c1 + [c2, c3, c4, c5])

        return cell
    }
}

Результат:

0
ответ дан Code Different 16 August 2018 в 00:12
поделиться

Выполните следующие действия:

  • Создайте новый класс и сделайте его подклассом UITableViewCell и назовите его чем-то вроде MyTableViewCell.
  • В вашем файле раскадровки щелкните свой TableView, затем в правой панели щелкните инспектор атрибутов, выберите ячейки прототипа: 1.
  • Нажмите вновь созданную ячейку и в инспекторе атрибутов выберите имя идентификатора (например, «myCellID»). Затем в инспекторе идентификации установите атрибут класса MyTableViewCell.
  • Перетащите текстовые поля в свою ячейку, затем с помощью помощника редактора, ctrl + click и перетащите его из текстовых полей в подкласс UITableViewCell. Он должен создавать выходы для ваших текстовых полей.
  • В вашем ViewController создайте свой класс для реализации протокола UITableViewDataSource и переопределите tableView(_: numberOfRowsInSection:) и tableview(_: cellForRowAtIndexPath:). Затем в последнем методе напишите: пусть myCell = tableView.dequeueReusableCellWithIdentifier («myCellID») как! MyTableViewCell возвращает myCell

Несмотря на то, что мы не используем выходы для созданных вами текстовых полей, вам нужно будет в какой-то момент использовать их для предварительного заполнения контента, установки методов целевого действия, и др.

0
ответ дан Diego 16 August 2018 в 00:12
поделиться
  1. Создайте подкласс UITableViewCell с двумя выводами текстового поля:
    class TextFieldsCell: UITableViewCell {
        @IBOutlet var textfield1: UITextField!
        @IBOutlet var textfield2: UITextField!
    }
    
  2. В IB выберите вид таблицы и добавьте ячейку прототипа в представление таблицы, установив «Prototype Cells» на «1», в инспекторе атрибутов:

  1. В IB разметьте текстовые поля внутри вашей ячейки, используя автозапуск. (пропуская детали реализации автоопределения)

  1. В IB выберите ячейку просмотра таблицы и измените ее «Идентификатор», в «TextFieldsCell», в инспекторе атрибутов:

  1. В IB выберите ячейку просмотра таблицы и измените ее " Класс "в" TextFieldsCell ", в инспекторе идентификации:

  1. В IB подключите IBOutlets TextFieldsCell к соответствующие текстовые поля:

  1. В вашем контроллере просмотра, который содержит представление таблицы, выполните следующее:
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: TextFieldsCell = tableView.dequeueReusableCellWithIdentifier("TextFieldsCell") as! TextFieldsCell
        return cell
    }
    
  2. Если вы правильно настроили все, вы должны увидеть это при следующем прогоне:

3
ответ дан Myxtic 16 August 2018 в 00:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: